首页 > 解决方案 > TypeError:无法读取 React 和 Redux 中未定义的属性“代码”

问题描述

我目前在我的 React 组件中有 jsx,它将根据对象中是否存在某个值返回某些特性。例如在我的 React 组件中:

if(customer.product.id === "543"){
    return (
      <div className="text-align-left">
        <div className="row">
          <div className="col-xs-12 font-weight-bold">
            <p>Some text here</p>
          </div>
        </div>
      </div>
    );
  } else {
    return (
      <div className="text-align-left">
        <div className="row">
          <p>Different text here</p>
          </div>
        </div>
      </div>
    );

'customer' 来自我的 Redux 状态并进行了适当的调度,如下所示:

{
  "product": {
    "id": "543",
  },
  "info": [
    {
      "name": {
        "title": "Mr",
        "first_name": "John",
        "last_name": "Smith",
      },
      "dob": "1956-06-06",
      "phone": [
        {
          "number": "5555555555",
          "ext": "234",
        }
      ]
    }
  ]
}

我知道它正在正确调度,因为如果我尝试访问 jsx 中的 customer.info[0].name.last_name,它会返回正确的值。

然而,当我尝试获取 customer.product.id 的值时,我遇到了错误

TypeError: Cannot read property 'id' of undefined

从这里阅读其他问题,似乎问题可能是我从 Redux 状态获取的对象是异步的,但如果它能够进入并访问 customer.info[0].name.last_name,为什么不能t 它对 customer.product.id 做同样的事情吗?我尝试使用 try catch 块,但这也没有成功(另外,在 try catch 中使用 if else 语句并不是完全干代码)。在使用 React 时,我在这里发现的许多其他问题都是处理具有本地状态的组件。

如果这个问题与另一个问题重复,我深表歉意,但我似乎找不到适合这种情况的问题。谢谢!

标签: javascriptreactjsobjectreduxreact-redux

解决方案


推荐阅读