javascript - 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 时,我在这里发现的许多其他问题都是处理具有本地状态的组件。
如果这个问题与另一个问题重复,我深表歉意,但我似乎找不到适合这种情况的问题。谢谢!
解决方案
推荐阅读
- android - 如何在kotlin的谷歌地图中放大一个位置?
- c - OpenVG:vgCreateImage 是否分配内存
- content-management-system - 如何在果园的 GraphQl 中关联 2 个内容项?
- python - 如何计算一个数字使用python打印了多少次?
- dataset - so_survey csv 在哪里或我如何找到它?
- firebase - 当我在 void main() 中初始化应用程序 firebase 时,它会为 web 引发一个错误,但它可以在 android 上正常工作
- google-kubernetes-engine - Fluentd 传递环境变量
- postgresql - 在函数内部,相同的查询需要 5 倍的时间 - 函数有什么问题?
- android - 我正在尝试使用 recyclerview 在屏幕上打印列表,但适配器部分中的代码不起作用
- http-status-code-404 - 发布我的 github 页面时如何修复错误 404?