【问题标题】:React typeerror: Cannot read property of undefined - But I can read other props just fine反应类型错误:无法读取未定义的属性-但我可以很好地读取其他道具
【发布时间】:2018-04-01 23:42:02
【问题描述】:

我对这个未定义的错误感到困惑。这是我可以从 render() 控制台登录的对象

{_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 的道具:颜色和大小。即使这会导致 typeError:

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

除了 options.color 和 options.size 之外,我在访问和渲染所有其他道具时都没有问题。有什么想法吗?

【问题讨论】:

  • 你想改变一个常量的值吗?
  • Lodash 很棒:const color = _.get(this.props.detail.options, 'color') || [];
  • 这非常有效。谢谢,蔡斯。 Palsrealm 的解决方案同样有效。

标签: javascript reactjs object react-redux


【解决方案1】:

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

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

试试看

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

【讨论】:

  • 谢谢,@palsrealm。这解决了问题! Chase 的 lodash 解决方案也有效。
  • 我喜欢这种更简洁的方式: const color = (this.props.detail.options || {}).color || [];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多