反应:类型错误:无法读取未定义的属性“newValue”

时间:2021-04-15 05:49:46

标签: 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 a const imported array
     return {
      id: data.id,
      name: data.name,
      value: financials[data.id]
      newValue: "",
     };
    });

  this.setState({
    values,
  });
}

但是,如果我在渲染时控制台.log values,第一个控制台日志将其显示为未定义,但下一个将其显示为已定义。我还可以在我的渲染方法中map values 没有任何问题。

render() {
    const {
      company,
      financials,
      values,
    } = this.state;

    console.log(values, "check")

我的问题是在我的渲染方法中,我调用了一个函数 {this.calculate(financial.id)}

 calculate(financial) {
    const { financials, values } = this.state;
    console.log(values, "values"); 
    let numerator;
    if (financial === "tev_profit") { //this line is okay
      let tev = values.find(o => o.id === "total_value");
      console.log(tev, "here"); 
      numerator = tev.newValue; //this line is causing error.

从控制台日志来看,似乎 tev 有时已定义,但有时未定义。我不确定我哪里出错了,因为我也将它添加到我的代码中,但仍然面临相同的类型错误:

this.calculate = this.calculate.bind(this);

更新: 在进入任何其他 if 块之前,我曾尝试将 if(values) 添加到我的 calculate 函数中,但遇到相同的错误

1 个答案:

答案 0 :(得分:1)

问题

如果未找到元素,

Array.prototype.find 可以返回 undefined

<块引用>

find() 方法返回第一个元素的值 提供的数组满足提供的测试功能。如果不 值满足测试函数,返回undefined

解决方案

在访问属性之前检查有效的 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;
  }