Reputation: 1791
This question has already been answered here but things are always changing.
componentWillReceiveProps is deprecated now and it will be removed soon.
So, what is the cleanest way to update a child component when the parent needs to fetch some data?
See the old question for more details.
Thanks
UPDATE:
Basically, the parent component fetches some data and the child component needs that data.
This is the child component.
class Dropdown extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
// This is deprecated so need to be replaced by your answer
componentWillReceiveProps(nextProps) {
this.setState({
value: nextProps._layouts[0]
});
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
render() {
// The options for the dropdown coming from the parent
const options = this.props._layouts.map((number) =>
React.createElement("option", null, number)
)
// This logs the value coming from the parent
// A timeout is needed since fetch is asynchronous
setTimeout(() => {
console.log(this.state.value)
}, 400);
// This is just a dropdown menu
return React.createElement("div",
null, React.createElement("span", {
class: "custom-dropdown"
}, React.createElement("select", {
onChange: this.handleChange,
}, options)));
}
}
Upvotes: 0
Views: 774
Reputation: 1512
The lifecycle method that replaced componentWillReceiveProps
is static getDerivedStateFromProps
. (Actually that's not entirely true, but you can achieve the same result with it)
The function is static, and receives the state and props of the component, and returning a new object to merge into the component's state.
But the real question is - do you really need it? The answer from the question above (slightly adjusted):
getDerivedStateFromProps(nextProps) {
return nextProps.data;
}
simply does nothing. You can just as well use the props instead of the state.
As the React doc says:
This method exists for rare use cases where the state depends on changes in props over time.
Upvotes: 0
Reputation: 537
You can use the shouldComponentUpdate(nextProps,nextState)
and return true
if the props
or state
changed in the parent.
More info in the react documentation
Upvotes: 1