[英]Updating a child component after the parent state changes
componentWillReceiveProps现在已过时,它将很快被删除。
那么,当父级需要获取一些数据时,更新子级组件的最干净方法是什么?
有关更多详细信息,请参见旧问题。
谢谢
更新:
基本上,父组件会获取一些数据,而子组件则需要该数据。
这是子组件。
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)));
}
}
您可以使用shouldComponentUpdate(nextProps,nextState)
并在父项中的props
或state
更改时返回true
。
替换componentWillReceiveProps
的生命周期方法是static getDerivedStateFromProps
。 (实际上这并不完全正确,但是您可以用它达到相同的结果)
该函数是静态的,并接收组件的状态和属性,并返回一个新对象以合并到组件的状态。
但是真正的问题是-您真的需要吗? 上面问题的答案(略有调整):
getDerivedStateFromProps(nextProps) {
return nextProps.data;
}
根本什么也没做。 您也可以使用道具代替状态。
正如React文档所说:
此方法适用于状态依赖于道具随时间变化的罕见用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.