简体   繁体   中英

how to set state in render react native

When i want to setState in render lifecycle it gives me this error

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());
    }
 }

You shouldn't use setState() inside the render() method because it triggers a re-render inside the render, throwing an error. The better way to do it is inside the componentDidMount() method, like this:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM