如何清除另一个函数中的setTimer

问题描述 投票:0回答:1

组件正在另一个文件中调用函数,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.
react-native
1个回答
0
投票

数据(即状态和道具)通常“向下”流到反应组件树,即父级到子级。如果孩子的兄弟姐妹需要访问其级别或更低级别的数据的解决方案是将数据“放样”到最接近的共同祖先(在这种情况下为父代)。换句话说,您需要跟踪父级中的计时器,以便其他子级组件可以通过道具接收对它的引用以取消它。

希望这可以说明它的概念:

父母

const setTimer = () => {
  this.timeout = setTimeout(() => {
  pressTwice = false;
}, duration);

render() {
  return (
    <>
      <ChildSetsTimer setTimer={this.setTimer} />
      <ChildClearsTimer timerRef={this.timeout} />
    </>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.