// Component
state = {
myState: []
}
// Using this method works fine:
componentWillReceiveProps(nextProps) {
this.setState({
myState: nextProps.myPropsState
})
}
// But using this method will cause the checkBoxes to be readonly:
static getDerivedStateFromProps(nextProps,prevProps) {
const { myPropsState: myState } = nextProps
return {
myState
}
}
// And here's checkBox
Box" id={`someid`}
onChange={(e) => this.handleMethod(e,comp.myState)}
checked={myState.indexOf(comp.myState) > -1} />
getDerivedStateFromProps is invoked right before calling the render
method,both on the initial mount and on subsequent updates. It should
return an object to update the state,or null to update nothing.
This method exists for rare use cases where the state depends on
changes in props over time. For example,it might be handy for
implementing a component that compares its prevIoUs and
next children to decide which of them to animate in and out.
Deriving state leads to verbose code and makes your components
difficult to think about. Make sure you’re familiar with simpler
alternatives:
If you need to perform a side effect (for example,data fetching
or an animation) in response to a change in props,use componentDidUpdate lifecycle instead.
If you want to re-compute some data only when a prop changes,use
a memoization helper instead.
If you want to “reset” some state when a prop changes,consider
either making a component fully controlled or fully uncontrolled
with a key instead.
static getDerivedStateFromProps(props,state) {
// Note we need to store prevPropsState to detect changes.
if (
props.myPropsState !== state.prevPropsState
) {
return {
prevPropsState: state.myState,myState: props.myPropsState
};
}
return null;
}