将UseRef与Debouncer一起使用时无法访问反应状态

时间:2020-05-09 23:02:27

标签: javascript node.js reactjs typescript react-hooks

我很难调试这里发生的问题。

我正在尝试使用反跳功能,以便用户可以在ReactQuil上键入内容,然后当他们停止键入一小段时间时,反跳功能会触发另一个函数以React Quil组件内部的状态更新数据库。但是,我失去了进入该州的权限!

我正在使用useRef来引用去抖动功能,以便当我clearTimeout时,它可以正确清除超时,并且不会产生多个“ clearTimeout”调用。

我无法在SaveNote()函数中打印出我的身体状态。它可以在UseEffect内正确打印,但在更新调用中会以某种方式丢失状态。

import React, { useEffect, useRef, useState } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

interface Props {
  selectedNote: any; // A note object, that has body and title
}

function Editor(props: Props) {
  const [body, setBody] = useState("");
  const [title, setTitle] = useState("");

  useEffect(() => {
    setBody(props.selectedNote.body);
    setTitle(props.selectedNote.title);
  }, []);

  useEffect(() => {
    console.log("this is the body before " + body); // <-- WORKS CORRECTLY
    update();
  }, [body]);

  const update = useRef(
    debounce(() => {
      console.log("debouncing!");
      saveNote();
    }, 2500)
  ).current;

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  function debounce(func: Function, delay: number, immediate?: any) {
    let timeoutID: NodeJS.Timeout;
    return function (...args: any) {
      if (timeoutID) {
        clearTimeout(timeoutID);
      }
      timeoutID = setTimeout(() => {
        func(...args);
      }, delay);
    };
  }

  function saveNote() {
    console.log("this is the body after " + body); // <-- DOES NOT WORKS CORRECT! I DON'T SEE ANYTHING
    console.log(body);
    // TODO: some API call here

  }

  function updateBody(val: any) {
    setBody(val);
  }

  return (
    <ReactQuill theme="snow" value={body} onChange={updateBody}></ReactQuill>
  );
}

export default Editor;

0 个答案:

没有答案