我如何实现反应的自动保存反应的输入更改



,所以问题是您有一个编辑器。
用户继续输入编辑器,他闲置了一段时间,大约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来记忆拒绝的功能。如果要在拒绝功能中使用editorState,则可以在调用debounced时从onEditStateChange方法传递它。另外,您需要纠正您的Debounce语法

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;

相关内容

  • 没有找到相关文章

最新更新