[英]ReactJs props returns undefined in componentDidMount
I have a problem with my props.我的道具有问题。
in my class, if I do :在我的课堂上,如果我这样做:
<Input type="text" name="firstName" id="firstName" placeholder="First Name" value={this.props.user.firstName}/>
that is working, my firstName appears.这是工作,我的名字出现。
but if I try :但如果我尝试:
componentDidMount = () => {
console.log("firstName : "+this.props.user.firstName)
}
that returns me undefined
, can someone help me ?返回我
undefined
,有人可以帮助我吗?
First off, componentWillReceiveProps
has been deprecated.首先,
componentWillReceiveProps
已被弃用。 So you might want to add UNSAFE_
to the method name.因此,您可能希望将
UNSAFE_
添加到方法名称中。 Note from documentation : 文档中的注释:
Note
笔记
This lifecycle was previously named componentWillReceiveProps.
这个生命周期以前被命名为 componentWillReceiveProps。 That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
该名称将继续有效,直到版本 17。使用 rename-unsafe-lifecycles codemod 自动更新您的组件。
Second, you don't define lifecycle methods as arrow functions.其次,您没有将生命周期方法定义为箭头函数。 You do it like this:
你这样做:
UNSAFE_componentWillReceiveProps(nextProps) {
console.log("firstName : " + this.props.user.firstName)
}
Best solution?最佳解决方案? This:
这个:
componentDidUpdate(prevProps) {
if (prevProps.user !== this.props.user) {
console.log(`firstName: ${this.props.user.firstName}`);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.