I have two components. A main and a child component.
Let's assume a function is triggered in the main component which cause its state
to be mutated. The state
of the main component is passed down to the child component as a prop. The newly updated data in the props
of the child component should now be used to to set the state
of the child component.
I can't do this on ``componentDidUpdate since it would cause an infinite loop. On the other hand I wouldn't want to lift the child's state
to the main component since most code of it would be useless in the main component.
I hope you can help
componentDidUpdate
takes prevProps
as argument componentDidUpdate(prevProps, prevState, snapshot)
. So to not getting the code in infinite loop, you can compare this.props
with prevProps
and update the state accordingly.
componentDidUpdate(prevProps) {
if(this.props.data !== prevProps.data) {
// update the new state here this will not cause infinite loop
}
}
You can use getDerivedStateFromProps
as mentioned in the React docs :
export default class Child extends Component {
static getDerivedStateFromProps(newProps, currentState) {
return {
value : newProps.value
}
}
render() {
return (
<div>
{/* Your layout */}
</div>
);
}
}
For a functional component using hooks.
function Child(props) {
const [whatever, setWhatever] = React.useState(props.whatever);
React.useEffect(() => {
setWhatever(props.whatever);
}. [whatever]);
}
export default Child;
Hope it helps.
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.