首页 > 解决方案 > 我如何在 React 中实现输入更改的去抖动自动保存?

问题描述

所以问题是假设你有一个编辑器。
用户一直在编辑器中输入,他会闲置一段时间,比如 5 秒。所以闲置5秒后,你向api发出网络请求,将他输入的内容保存在数据库中。它应该在空闲 5 秒后只发出一个请求。

我完成了,但它提出的请求等于字数。如果你输入 like 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;

标签: javascriptreactjslodashreact-hooksdebounce

解决方案


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

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;

推荐阅读