ReactJs 道具 returns 在 componentDidMount 中未定义

ReactJs props returns undefined in componentDidMount

我的道具有问题。

在我的 class 中,如果我这样做:

<Input type="text" name="firstName" id="firstName" placeholder="First Name" value={this.props.user.firstName}/>

有效,我的名字出现了。

但如果我尝试:

componentDidMount = () => {
    console.log("firstName : "+this.props.user.firstName)
 }

那个 returns 我 undefined,有人可以帮我吗?

首先,componentWillReceiveProps 已被弃用。因此,您可能希望将 UNSAFE_ 添加到方法名称中。来自 documentation 的注释:

Note

This lifecycle was previously named componentWillReceiveProps. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.

其次,您没有将生命周期方法定义为箭头函数。你这样做:

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}`);
  }
}