我的道具有问题。
在我的课堂上,如果我这样做:
<Input type="text" name="firstName" id="firstName" placeholder="First Name" value={this.props.user.firstName}/>
正在工作,我的名字出现。
但是,如果我尝试:
componentDidMount = () => {
console.log("firstName : "+this.props.user.firstName)
}
返回我undefined
的人可以帮助我吗?
答案 0 :(得分:5)
首先,componentWillReceiveProps
已被弃用。因此,您可能想将UNSAFE_
添加到方法名称。来自documentation的注释:
注意
此生命周期以前称为componentWillReceiveProps。那 名称将一直使用到版本17。使用 重命名不安全生命周期codemod以自动更新您的 组件。
第二,您没有将生命周期方法定义为箭头函数。您是这样做的:
UNSAFE_componentWillReceiveProps(nextProps) {
console.log("firstName : " + this.props.user.firstName)
}
最佳解决方案?这个:
componentDidUpdate(prevProps) {
if (prevProps.user !== this.props.user) {
console.log(`firstName: ${this.props.user.firstName}`);
}
}