Reputation: 169
When a parent component passes a props named title to a child component and puts the props into the child component's state, when the parent component's title is moved to the child component instead, the props is updated, but the state is not updated and the past title is retained.
Props are updated, but the State using Props is not updated.
How do I update the state of a child component when the parent component is updated?
constructor() {
super();
this.state = {
title:''
};
}
<Child title={this.state.title}/>)}
constructor(props) {
super(props)
this.state = {
title: props.title
};
}
Upvotes: 1
Views: 65
Reputation: 19863
Copying props to state seems redundant and anti-pattern, but if you need to do it (for reasons like editing details in a form), you can copy the props into state using constructor
and update (conditionally) it when the props' value is changed using componentDidUpdate
lifecycle method:
class Child extends Component {
constructor(props) {
super(props);
this.state = {
title: this.props.title // Copy
};
}
componentDidUpdate(prevProps, prevState) {
if (this.props.title !== prevProps.title) {
this.setState({
title: this.props.title // Update conditionally when it is changed in props
});
}
}
render() {
return <>{this.state.title}</>;
}
}
Upvotes: 1
Reputation: 371193
Don't store the same state in multiple locations; synchronizing them will be a pain. Instead, pass down the title and a state setter function to the child, eg:
<Child
title={this.state.title}
setTitle={title => { this.setState({ title }); }}
/>
And don't keep state in the child - only use the title
prop. Call the setTitle
prop when you need to update from the child.
Upvotes: 2