簡體   English   中英

如何在渲染反應本機中設置狀態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM