gpt4 book ai didi

javascript - 如何在渲染 react native 中设置状态

转载 作者:行者123 更新时间:2023-11-28 17:28:24 26 4
gpt4 key购买 nike

当我想在渲染生命周期中设置状态时,它给了我这个错误

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 to 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
}

关于javascript - 如何在渲染 react native 中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com