Reactjs 无法读取未定义的属性,但该属性已定义
我有这个componentDidMount功能:Reactjs 无法读取未定义的属性,但该属性已定义,reactjs,mount,Reactjs,Mount,我有这个componentDidMount功能: componentDidMount() { const { insurances } = this.props; const insuranceId = this.props.match.params.id; const insurance = insurances.find(insurance => insurance.id == insuranceId); this.setState({ insura
componentDidMount() {
const { insurances } = this.props;
const insuranceId = this.props.match.params.id;
const insurance = insurances.find(insurance => insurance.id == insuranceId);
this.setState({ insurance: insurance }, () => {
console.log("insurance", this.state.insurance.tip); <--- this is what i am talking about
});
}
但是如果我执行console.log(this.state.insurance)
返回一个具有未定义属性的对象
编辑2
我认为这与我所说的很接近,你定义你的状态的方式就是问题所在 你把它当作
state = {
insurance: [
{
tip: "1"
}
]
};
将其更改为:
state = {
insurance:
{
tip: "1"
}
};
要作为this.state.insurance.tip访问它,它需要是保险对象中的一个键。您现在拥有的是此.state.insurance[0]。提示
因为保险现在是一个阵列
lmk,如果这需要更多的澄清。您定义状态的方式就是问题所在 你把它当作
state = {
insurance: [
{
tip: "1"
}
]
};
将其更改为:
state = {
insurance:
{
tip: "1"
}
};
要作为this.state.insurance.tip访问它,它需要是保险对象中的一个键。您现在拥有的是此.state.insurance[0]。提示
因为保险现在是一个阵列
lmk,如果这需要更多说明。您正在
this.setState
中传递回调函数,但仍然使用this.state
。新状态作为第一个参数提供。您可以将此作为回调进行尝试:(state)=>console.log(state.insurance.tip)
在调用setState
以验证其设置是否正确之前,是否可以console.log
退出insurance
?如果您的insurance
未设置,您仍然将状态设置为{insurance:undefined}
的对象。我编辑了答案,以便更容易阅读。这很奇怪。考虑一下在A中创建A,这样会更容易帮助别人。您能提供一个codesandbox版本或类似于您的代码的东西来查看发生了什么吗?我做了一个快速的演示来验证setState
回调是否如预期的那样工作:您可以看到,在控制台中,回调函数注销了this.state
,并且精确到最新的状态。我能得出的唯一结论是,当您设置state时,您的保险对象没有定义……您正在this.setState
中传递回调函数,但您仍然使用this.state
。新状态作为第一个参数提供。您可以将此作为回调进行尝试:(state)=>console.log(state.insurance.tip)
在调用setState
以验证其设置是否正确之前,是否可以console.log
退出insurance
?如果您的insurance
未设置,您仍然将状态设置为{insurance:undefined}
的对象。我编辑了答案,以便更容易阅读。这很奇怪。考虑一下在A中创建A,这样会更容易帮助别人。您能提供一个codesandbox版本或类似于您的代码的东西来查看发生了什么吗?我做了一个快速的演示来验证setState
回调是否如预期的那样工作:您可以看到,在控制台中,回调函数注销了this.state
,并且精确到最新的状态。我能得出的唯一结论是,当您设置状态时,您的保险对象没有定义。。。