gpt4 book ai didi

javascript - ReactJs props 在 componentDidMount 中返回未定义

转载 作者:行者123 更新时间:2023-11-28 14:09:51 25 4
gpt4 key购买 nike

我的 Prop 有问题。

在我的类里面,如果我这样做:

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

工作正常,我的名字出现了。

但如果我尝试:

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

返回给我未定义,有人可以帮助我吗?

最佳答案

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

关于javascript - ReactJs props 在 componentDidMount 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59981694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com