在setTimeout中更新状态(React和React-Native)

Hir*_*oki 1 javascript reactjs react-native

我一直试图实现的是state基于Javascript的计时器更新并再次更新相同的状态.

我无法实现这一点的原因似乎是stateReact.js 的本质.

这是我的实验片段......

render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}
Run Code Online (Sandbox Code Playgroud)

所以,目标是改变状态only just a few seconds if there is a specific props provided.

如果this.props.hasError过于频繁地更新,这种方法似乎达到了更新状态的极限.

如果这个问题太基础,请道歉.任何建议将不胜感激.

Tim*_*Tim 6

您不应该在render()函数中更新您的状态.如果你这样做,你将最终陷入无限循环,这就是你得到那个错误的原因.你需要使用:

componentWillReceiveProps(nextProps){
    if (this.nextProps.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题.