【问题标题】:React: TypeError: Cannot read property 'newValue' of undefined反应:TypeError:无法读取未定义的属性“newValue”
【发布时间】:2021-07-10 03:54:19
【问题描述】:

我在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 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 有时已定义,但有时未定义。我不确定我哪里出错了,因为我也将它添加到我的代码中,但仍然面临相同的 typeError:

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

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案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;
      }
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 2020-09-07
      • 2021-06-22
      • 2017-01-01
      • 2021-01-16
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多