首页 > 解决方案 > 无论页面如何,都会调用组件内部的 setTimeout

问题描述

我有一个 setTimeout 调用,每 5 分钟调用一次。问题是,无论我在哪个页面上,超时仍然会被调用并且正在进行 api 调用。

我的 setTimeout 组件位于主页内,理想的做法是在不再位于主页上时仅杀死该组件。我想避免破坏主页组件而不必重新获取数据。

我的 setTimeout 代码是这样的:

    sendCords(){
       this.props.actions.findCords()
       this.beginTimeout()
    }

    beginTimeout(){
       let timer = setTimeout(this.sendCords,300000);
       this.setState({timer});
    }

注意:生命周期钩子 EG componentWillUnMount 没有被调用,因为页面就像一个堆栈 - 并且页面没有卸载。我正在使用 react-native-router-flux

任何帮助将非常感激。

标签: react-nativereduxreact-native-router-flux

解决方案


好吧,我最终不得不做一些事情,在我的操作中,我会检查我正在调用的页面,如果没有在主页上调用它,则发送一个空操作。这将触发清除超时。需要对我的组件进行强制刷新

<Comp refresh={() => this.setState({val:!this.state.val} />

然后我会在导航回主页并需要再次设置超时时使用 shouldComponentUpdate :

shouldComponentUpdate(nextProps, nextState){
    if(this.props.removeTimer && !nextState.removeTimer){
        this.timeOutFunc()
}

推荐阅读