Javascript 反应:类型错误:无法读取属性';新价值';未定义的
我在Javascript 反应:类型错误:无法读取属性';新价值';未定义的,javascript,reactjs,Javascript,Reactjs,我在componentDidMount componentDidMount() { const company = this.props.location.state.company; const financials = this.props.location.state.financials; let { values } = this.state; values = EDITABLES.map((data) => { //EDITABLES is
componentDidMount
componentDidMount() {
const company = this.props.location.state.company;
const financials = this.props.location.state.financials;
let { values } = this.state;
values = EDITABLES.map((data) => { //EDITABLES is a const imported array
return {
id: data.id,
name: data.name,
value: financials[data.id]
newValue: "",
};
});
this.setState({
values,
});
}
但是,如果我在渲染时将值记录到console.log中,则第一个控制台日志显示为未定义,而下一个控制台日志显示为已定义。我还能够在渲染方法中映射值,没有任何问题
render() {
const {
company,
financials,
values,
} = this.state;
console.log(values, "check")
我的问题是,在我的render方法中,我调用了一个函数{this.calculate(financial.id)}
从控制台日志来看,似乎有时定义了tev
,但有时没有定义。我不确定哪里出错了,因为我也在代码中添加了这个,但仍然面临相同的类型错误:
this.calculate = this.calculate.bind(this);
更新:
在进入任何其他if块之前,我曾尝试将if(values)
添加到我的calculate
函数中,但得到了相同的错误问题
如果未找到元素,则可以返回未定义的
find()
方法返回
提供的阵列满足提供的测试功能。如果没有
值满足测试函数,则返回未定义的
解决方案
在访问属性之前,请检查有效的tev
对象
if (financial === "tev_over_ltm_gross_profit") {
const tev = values.find(o => o.id === "total_enterprise_value");
if (tev) {
// tev exists
numerator = tev.newValue;
}
if (financial === "tev_over_ltm_gross_profit") {
const tev = values.find(o => o.id === "total_enterprise_value");
if (tev) {
// tev exists
numerator = tev.newValue;
}