我如何在 React 中实现输入更改的去抖动自动保存?

How can i implement debounced auto save on input change in React?

所以问题是假设您有一个编辑器。
用户不停地在编辑器中输入,然后他闲置了大约 5 秒钟。因此,在闲置 5 秒后,您向 api 发出了一个网络请求,以将他输入的内容保存到数据库中。它应该在空闲 5 秒后只发出一个请求。

我完成了,但它提出的要求与字数相等。如果您键入 asdf ,它会发出四个 api 请求。在我的示例中,四个 console.log();

const EditorComponent = () => {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  // I need another logic which checks the time difference of idling.

  const debounced = () => {
    return debounce(() => {
      console.log("the api is going to call after 5 seconds");
    }, 5000);
  };

  const onEditorStateChange = value => {
    const rawContent = convertToRaw(value.getCurrentContent());
    const markdown = draftToMarkdown(rawContent);
    setEditorState(value);
    debounced()
  };

  return (
    <div style={{ width: "500px" }}>
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={onEditorStateChange}
      />
    </div>
  );
};

export default EditorComponent;

问题是在每次渲染时都会创建一个新的去抖功能,因此 API 会被多次调用。您必须使用 useCallback 来记忆去抖功能。如果你想在 debounced 函数中使用 editorState,你可以在调用 debounced 时从 onEditStateChange 方法传递它。您还需要更正去抖动语法

const EditorComponent = () => {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  // I need another logic that checks the time difference of idling.

  const debounced = useCallback(debounce(() => {
      console.log("the api is going to call after 5 seconds");
  }, 5000), []);

  const onEditorStateChange = value => {
    const rawContent = convertToRaw(value.getCurrentContent());
    const markdown = draftToMarkdown(rawContent);
    setEditorState(value);
    debounced()
  };

  return (
    <div style={{ width: "500px" }}>
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={onEditorStateChange}
      />
    </div>
  );
};

export default EditorComponent;