首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应超时和清除超时

反应超时和清除超时
EN

Stack Overflow用户
提问于 2019-07-25 07:59:24
回答 1查看 345关注 0票数 2

我有一个没有设置为组件的React页面。我希望使用React Hooks,如useEffect或任何其他建议。本质上,我需要清除我的超时。

代码语言:javascript
复制
const ExamplePage = ({
  test1, test2, test3
}: Props) => {
  const setClipboardTimer = (index, copied, show, delay) => {
    const timer = setTimeout(() => {
      setClipboardData(index, copied, show);
    }, delay);
    // How can I clear my timer on componentWillUnmount
  };

  const copyToClipboard = (copy, index) => {
    copyTextToClipboard(copy);
    setClipboardData(index, true, true);
    setClipboardTimer(index, true, false, 2500);
    setClipboardTimer(index, false, true, 3000);
  };
};
EN

回答 1

Stack Overflow用户

发布于 2019-07-25 09:23:09

由于我不知道其他函数(如copyTextToClipboard、setClipboardData ...etc)在状态方面的作用,更容易利用和测试计时器的方法是使用组件类。

例如,这是一个简单的组件类,它将渲染延迟5秒:

代码语言:javascript
复制
class Timer extends Component {
    state = { requestTimeout: false };

    // **optional** only rerenders the component if the requestTimeout state has been changed
    // this ensures that other state/props changes and/or a parent component 
    // that has its own updating state, won't update this component
    shouldComponentUpdate = (nextProps, nextState) =>
        nextState.requestTimeout !== this.state.requestTimeout);

    // if the component unloads before the 5000ms timeout, clear it
    componentWillUnmount = () => this.clearTimer();

    // a class field to clear the timer that was set in this.requestTimeout
    clearTimer = () => clearTimeout(this.requestTimeout);

    // a class field to update state and clear the timeout
    requestTimedout = () =>
        this.setState({ requestTimeout: true }, () => this.clearTimer());

    // a class field to set this.requestTimeout to a timer that will trigger 
    // this.requestTimedout after a 5000ms delay
    setRequestTimer = () => 
        this.requestTimeout = setTimeout(this.requestTimedOut, 5000);

    // if requestTimeout state is true (?) show hello (:) else show loading
    render = () => this.state.requestTimeout ? <p>Hello</p> : <p>Loading...</p>
}

当你开始处理钩子时,当一个挂载的功能组件在计时器仍在运行时更新时,你需要一种方法来持久化相同的计时器(否则,每次功能组件重新渲染时,它都会继续生成新的计时器)。

例如,我有一个涉及使用setIterval的演示here。正如您所看到的(单击源< >按钮),当功能组件的状态被更新时,它涉及到利用useRef对象来保持相同的setInterval计时器。然后,我利用几个回调函数来设置/暂停/清除间隔。此外,它还利用useEffect钩子检查它是否仍在运行,如果还在运行,它将在return语句中将其清除。

简而言之,虽然您可以使用setTimeout在我的setIterval钩子演示中实现相同的功能,但我发现类更易于使用和理解(特别是当状态正在更新并且需要同步处理时)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57192644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档