当我想在渲染生命周期中设置状态时,它给了我这个错误
Warning: Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.
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
}
关于javascript - 如何在渲染 react native 中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022278/