【问题标题】:Unable to read the following JSON object, gives undefined even though element exists无法读取以下 JSON 对象,即使元素存在也给出未定义
【发布时间】:2020-04-10 07:18:24
【问题描述】:

我有以下对象(在里面操作了一些点之后) 我称之为 props.stuff , 给定:数据从父组件传递到子组件为

//Parent
componentDidMount() {
    this.getData();
  }

  async getData() {
    const res = await axios.get(
      "{link here}"
    );
    const { data } = await res;
    this.setState({ stuff: data});
  }

<Child props={this.state.stuff} />

所以,当我做 console.log(props.stuff):

props.stuff= {
"date":"November 14",
"status":"PENDING",
"id":"146859",
"invoice_number":"123685479624",
"amount":"950.00",
"currency":"$"
}

但尝试访问 props.stuff.date(或类似 props.stuff.{element} 的东西)给了我undefined。 我做错了什么?

注意:我通过执行 console.log(JSON.stringify(props.stuff)) 得到了下面的字符串,所以这正是它。

【问题讨论】:

标签: javascript json reactjs string


【解决方案1】:

所以我终于找到了解决方案。实际上,道具是从父组件传递给子组件的,而在父组件中,它是通过 API 调用获取的。所以 props 的初始值是不确定的。

在父组件中,写:

{props.stuff && <Child stuff={props.stuff} />}

这确保只有当它存在时才会传递道具,从而解决了问题

【讨论】:

  • 这样的基本错误
猜你喜欢
  • 2017-11-10
  • 1970-01-01
  • 2022-01-25
  • 2023-04-10
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多