javascript - react 类型错误 : Cannot read property of undefined - But I can read other props just fine

标签 javascript reactjs object react-redux

我对这个未定义的错误感到困惑。这是我的对象,我可以从 render() console.log

{_id: "59e7ac89d14e6d644588eaff", title: "500 thread count sateen sheet set", id: "1233", description: "Sink into dreamland with a luxe sheet set in smoot…at and fitted sheets, along with two pillowcases.", type: "Duvet", …}
addedDate
:
"2017-10-18T19:33:29.468Z"
collectiontype
:
"String"
description
:
"Sink into dreamland with a luxe sheet set in smooth, lustrous organic-cotton sateen that includes flat and fitted sheets, along with two pillowcases."
holiday
:
""
id
:
"1233"
image1
:
{_id: "59e7ac89d14e6d644588eafd"}
image2
:
{_id: "59e7ac89d14e6d644588eafe"}
options
:
{color: Array(2), size: Array(5)}
price
:
(4) [89, 99, 119, 129]
season
:
"All"
subtype
:
""
tags
:
[""]
title
:
"500 thread count sateen sheet set"
type
:
"Duvet"
__v
:
0
_id
:
"59e7ac89d14e6d644588eaff"
__proto__
:
Object

在第一次渲染时,对象实际上是未定义的。我通过将每个属性分配给一个空类型来处理这个问题。例如:

const price = this.props.detail.price || []

出于某种原因,无论我做什么,我都无法访问选项 obj 的属性:颜色和大小。即使这样也会导致类型错误:

const color = this.props.detail.options.color || []

除了 options.color 和 options.size 之外,我可以毫无问题地访问和渲染所有其他 Prop 。有什么想法吗?

最佳答案

当你这样做时你的选项对象是未定义的

const color = this.props.detail.options.color || []

尝试做

const color= this.props.detail.options? this.props.detail.options.color || [] :[];

关于javascript - react 类型错误 : Cannot read property of undefined - But I can read other props just fine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855238/

相关文章:

javascript - 使用 Object.assign 替换状态

reactjs - 关于useEffect中的无限循环

java - 使用 toString() 方法打印 String Array 对象的编号列表

java - 从数组内的类调用方法

node.js - Webpack react 错误 : Module parse failed: Unexpected token

ios - swift - 如何修改另一个类的对象的属性?

javascript - 切片链接 JavaScript

javascript - 如何转换非 HTML 4 实体来显示?

javascript - 使用 Chart.js 将日期作为 x 轴标签

javascript - 如何从 Node.Js 中的字符串创建流?