prevstate react code example
Example 1: react prevstate
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
Example 2: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
if (prevState.pokemons !== this.state.pokemons) {
console.log('pokemons state has changed.')
}
}
Example 3: prevstate in usestate
const [prevState, setState] = React.useState([]);
setState(prevState => [...prevState, 'somedata'] );
Example 4: this.setstate prevstate
this.setState(prevState => ({ n: !prevState.n }))
Example 5: prev props
componentDidUpdate(prevProps) {
// Utilisation classique (pensez bien à comparer les props) :
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
Example 6: prevstate in react
handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}