【发布时间】:2019-07-12 04:26:40
【问题描述】:
这个问题已经回答了here,但事情总是在变化。
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)));
}
}
【问题讨论】:
-
父级获取数据并更新自己的状态...状态(或它的一部分通过道具传递给子级...状态更新,道具更新...否这里根本需要生命周期方法...如果您需要对重新渲染进行更精细的控制,请在此处查看每个用例可用的方法:reactjs.org/docs/react-component.html#updating
-
Re “请参阅旧问题了解更多详细信息。”,您的问题应该是独立的,而不是依赖于任何其他问题。如果另一个问题被关闭怎么办?如果您的问题需要更多详细信息,请嵌入它们而不是链接到其他地方。
-
@skomisa 我更新了答案。请告诉我是否需要更改任何内容。
标签: reactjs