猿问

如何在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;


弑天下
浏览 197回答 1
1回答

凤凰求蛊

问题在于,在每个渲染上都会创建一个新的去抖动功能,因此会多次调用这些API。您必须useCallback用来记忆去抖功能。如果要editorState在已删除反跳的函数中使用,可以onEditSatateChange在调用时将其从方法传递debounced。另外,您需要更正您的反跳语法const EditorComponent = () => {&nbsp; const [editorState, setEditorState] = React.useState(&nbsp; &nbsp; EditorState.createEmpty()&nbsp; );&nbsp; // I need another logic which checks the time difference of idling.&nbsp; const debounced = useCallback(debounce(() => {&nbsp; &nbsp; &nbsp; console.log("the api is going to call after 5 seconds");&nbsp; }, 5000), []);&nbsp; const onEditorStateChange = value => {&nbsp; &nbsp; const rawContent = convertToRaw(value.getCurrentContent());&nbsp; &nbsp; const markdown = draftToMarkdown(rawContent);&nbsp; &nbsp; setEditorState(value);&nbsp; &nbsp; debounced()&nbsp; };&nbsp; return (&nbsp; &nbsp; <div style={{ width: "500px" }}>&nbsp; &nbsp; &nbsp; <Editor&nbsp; &nbsp; &nbsp; &nbsp; editorState={editorState}&nbsp; &nbsp; &nbsp; &nbsp; toolbarClassName="toolbarClassName"&nbsp; &nbsp; &nbsp; &nbsp; wrapperClassName="wrapperClassName"&nbsp; &nbsp; &nbsp; &nbsp; editorClassName="editorClassName"&nbsp; &nbsp; &nbsp; &nbsp; onEditorStateChange={onEditorStateChange}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; );};export default EditorComponent;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答