如何在渲染反应本机中设置状态

时间:2018-06-25 11:20:13

标签: javascript reactjs 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());
    }
 }

1 个答案:

答案 0 :(得分:3)

您不应该在setState()方法内使用render(),因为它会触发渲染内部的重新渲染,并引发错误。更好的方法是在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
}
相关问题