【发布时间】:2018-11-07 00:27:13
【问题描述】:
我正在尝试将一些数据作为道具从父组件传递到子组件,并且我想将此道具设置为初始状态。
class EditContact extends Component {
constructor(props) {
super(props);
this.state = {
name: this.props.name,
phone_number: this.props.phone_number,
address: this.props.address
};
this.handleInputChange = this.handleInputChange.bind(this);
}
...
}
我没有收到任何错误,但如果我 console.log this.state.name 我什么也得不到。或者当我在 chrome-s react add-on 中检查它时 我可以看到 props 值,但状态仍然是 ""。
我也尝试在componentDidMount 中使用getDerivedStateFromProps 对其进行排序,我可以使用它进行设置,但是它不允许我稍后更改状态...为什么? !有什么问题?
【问题讨论】:
-
你是如何在你的应用程序中使用这个
EditContact组件的?可能是您正在异步加载父组件中的数据,因此在创建EditContact时,尚未设置道具。 -
请提供您要尝试的代码
console.log
标签: reactjs setstate getderivedstatefromprops