Reputation: 688
I am more familiar with functional components, but I have to fix some class components that were built earlier. What I am trying to do is,
useEffect(() => {
if (state1) {
// do this
// change state state1 -> false
}
}, [state1])
something like this in a class component. What I tried was
componentWillReceiveProps = (nextProps) => {
if (nextProps.state1 !== this.props.state1) {
if (nextProps.state1) {
// do this
} else {
// revert this
}
// update state
this.setState({ state1: !this.state.state1 });
}
}
Obviously, this is weird. But I was confused because the componentWillReceiveProps
receives a prop
as a parameter. So, I am not sure how I am supposed to put in a state to detect changes in states.
Any help?
Upvotes: 1
Views: 60
Reputation: 84957
You probably want to use componentDidUpdate, not componentWillReceiveProps. componentWillReceiveProps is going to be removed from react, and it often gets misused.
With componentDidUpdate, you will do something like this:
componentDidUpdate(prevProps, prevState) {
if (this.state.state1 !== prevState.state1) {
if (this.state.state1) {
// do this
// change state state1 -> false
this.setState({ state1: false });
}
}
}
You may need to do similar code in componentDidMount if you need this code to run after the first render too.
Upvotes: 3