Javascript 在setTimeout内更新状态(React和React Native)
我一直试图实现的是更新Javascript 在setTimeout内更新状态(React和React Native),javascript,reactjs,react-native,Javascript,Reactjs,React Native,我一直试图实现的是更新状态,并根据Javascript的计时器再次更新相同的状态 我无法做到这一点的原因似乎是React.js中的state 这是我的一个实验片段 render() { if (this.props.hasError) { setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000); } return ( <View>
状态
,并根据Javascript的计时器再次更新相同的状态
我无法做到这一点的原因似乎是React.js中的state
这是我的一个实验片段
render() {
if (this.props.hasError) {
setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
}
return (
<View>
<Blah warning={this.state.showWarning} />
</View>
);
}
render(){
if(this.props.hasError){
setTimeout(函数(){this.setState({showWarning:true});}.bind(this),3000);
}
返回(
);
}
因此,目标是在提供特定道具的情况下,仅在几秒钟内更改的状态
如果This.props.hasError
更新得太频繁,这种方法似乎达到了更新状态的极限
如果这个问题太基本,我道歉。
任何建议都将不胜感激。您不应该在render()函数中更新您的状态。如果你这样做,你将在一个无限循环中结束,这就是为什么你会得到那个错误。您需要使用:
componentWillReceiveProps(nextProps){
if (this.nextProps.hasError) {
setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
}
}
这将解决您的问题 您正在超时内使用函数这将更改其作用域使用arow函数
顺便说一句,我已经相应地修改了你的代码
componentWillReceiveProps(nextProps) {
if(nextProps.hasError != this.props.hasError){
this.setState({
showWarning:nextProps.hasError
});
setTimeout(()=> {
this.setState({
showWarning:!this.props.showWarning
});
}, 3000);
}
}
render() {
return (
<View>
{this.state.showWarning?<Blah warning={this.state.showWarning} />:null}
</View>
);
}
组件将接收道具(下一步){
if(nextrops.hasError!=this.props.hasError){
这是我的国家({
showWarning:nextProps.hasError
});
设置超时(()=>{
这是我的国家({
showWarning:!this.props.showWarning
});
}, 3000);
}
}
render(){
返回(
{this.state.showWarning?:null}
);
}
有两个目的。一个是改变这张照片的背景色
组件3秒钟,另一个是显示消息,这是
位于(同样,持续3秒)
由于您只希望这些更改显示3秒钟,因此必须先设置它们,然后使用setTimeout在3秒钟后将状态设置为相反的状态
从您的代码判断,this.props.hasrerror
是一个布尔值,因此我们可以首先设置showWarning
:
constructor(props){
super(props);
this.state = {showWarning: this.props.hasError}
}
当组件渲染时,它将显示当前状态,3秒后,我们将更改状态:
componentDidMount(){
setTimeout(() => {
this.setState({showWarning: false});
}, 3000);
}
乔萨尼拉切塔:你到底想用这个达到什么目的?有两个目的。一个是更改此组件的背景色3秒钟,另一个是显示位于
中的消息(同样,3秒钟)。