[英]how to set state in render react native
当我想在渲染生命周期中使用setState时,会出现此错误
警告:在现有状态转换期间(例如在
render
或其他组件的构造函数中)无法更新。 渲染方法应该纯粹是道具和状态的函数; 构造函数的副作用是反模式,但是可以将其移至componentWillMount
。
changeInitial(){
this.setState({initialLoad: false});
}
render() {
if (this.state.initialLoad) {
Animated.timing(this.state.listPosition, {
toValue: 350,
duration: 2000,
}).start(() => this.changeInitial());
}
}
您不应该在render()
方法内使用setState()
,因为它会触发渲染内部的重新渲染,并引发错误。 更好的方法是在componentDidMount()
方法内部,如下所示:
changeInitial(){
this.setState({initialLoad: false});
}
componentDidMount(){
if (this.state.initialLoad) {
Animated.timing(this.state.listPosition, {
toValue: 350,
duration: 2000,
}).start(() => this.changeInitial());
}
}
render() {
// Your component template here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.