console.log of editorState on unfocus 显示所有更改的堆栈

console.log of editorState on unfocus display a stack of all the changes

请先检查这个codesandbox

我使用 draftjs 编写了一个 TextEditor 组件,它获得了 3 个属性:

如果您查看我使用 TextEditor 组件的 App 组件,我会以使用 onChange.

更新的状态存储文本

TextEditor 外点击(蓝色背景)将触发 onUnfocus 函数 console.log text 状态。

但是如果我写了一个词(比方说 Hello),然后在 TextEditor 之外单击,我会得到很多 console.log 的变化:

> H
> He
> Hel
> Hell
> Hello

预期的行为是有一个 console.log 具有最新的变化:

> Hello

有人知道为什么我得到这么多 console.log 吗?

问题是您忘记了 return 您的 useEffect 助手,也没有将 text 作为依赖项传入,因此永远不会调用清理代码,所以每次呈现时都会添加另一个 document.addEventListener 而不会删除前一个。

React.useEffect(() => {
  return onClickOutsideHook( // add return here
    editorRef,
    (): void => {
      if (isFocus && onUnfocus !== undefined) {
        onUnfocus();
      }

      setIsFocus(false);
    }
  );
}, [editorState, isFocus, onUnfocus, text]); // add text as dependency