reactjs - 在父状态更改后更新子组件
问题描述
这个问题已经在这里得到了回答,但事情总是在变化。
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)
和返回。true
props
state
推荐阅读
- java - 无法使用 Java 中的 RDS 连接到 MySQL/Aurora:路径未与任何信任锚链接
- c - 有没有办法在 C 编程中的 for 循环中编写 switch 语句
- sql - Fiware量子闰日查询
- power-automate - 如何创建 Power Automate 流以在 sharepoint 中复制项目并将其粘贴到网络驱动器
- oracle - 一个提取泵到多个目标,在 oracle 金门中加密
- kibana - Kibana 不显示大文本
- scala - ScalaTest:表驱动属性检查的 BeforeAll
- python - 如何使用 celery beat 从 RabbitMQ 队列调度任务?
- python - 根据 2 列条件返回新列中的值
- database-design - 如何在 Cosmos DB 中对订单进行分区?