Reputation: 18863
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 tocomponentWillMount
.
changeInitial(){
this.setState({initialLoad: false});
}
render() {
if (this.state.initialLoad) {
Animated.timing(this.state.listPosition, {
toValue: 350,
duration: 2000,
}).start(() => this.changeInitial());
}
}
Upvotes: 0
Views: 5379
Reputation: 3403
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
}
Upvotes: 4