一个组件正在调用另一个文件中的函数,setTimer用于更新变量:
timer.js
const timer = () => {
  this.timeout = setTimeout(() => {
    pressTwice = false;
  }, duration);
};timerUI.js
componentDidMount() {
    timer();
  }
  componentWillUnmount() {
    clearTimeout(this.timeout);// how to clean the this.timeout?
  }我得到了这个错误:
Can't perform a React state update on an unmouted component.发布于 2019-10-02 22:39:13
数据(即状态和属性)通常在react组件树中“向下”流动,即从父到子。如果孩子的兄弟姐妹需要访问其级别或更低级别的数据,解决方案是将数据“放样”到最接近的共同祖先,在本例中是父祖先。换句话说,您需要跟踪父组件中的计时器,以便不同的子组件可以通过props接收对它的引用来取消它。
希望这说明了它的概念:
父级
const setTimer = () => {
  this.timeout = setTimeout(() => {
  pressTwice = false;
}, duration);
render() {
  return (
    <>
      <ChildSetsTimer setTimer={this.setTimer} />
      <ChildClearsTimer timerRef={this.timeout} />
    </>
  );
}https://stackoverflow.com/questions/58202885
复制相似问题