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

时间:2019-05-03 06:31:11

标签: javascript reactjs lodash react-hooks debounce

所以问题是,假设您有一个编辑器。
用户不断在编辑器中输入内容,他空闲了大约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;

1 个答案:

答案 0 :(得分:2)

问题是在每个渲染器上都会创建一个新的去抖动功能,因此会多次调用这些API。您必须使用useCallback来记住去抖动功能。如果要在去抖动的函数中使用editorState,则可以在调用onEditSatateChange时从debounced方法中将其传递。另外,您需要更正反跳语法

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

  // I need another logic which 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;