【问题标题】:nested object becoming undefined when trying to acces its properties嵌套对象在尝试访问其属性时变得未定义
【发布时间】:2020-04-05 13:32:40
【问题描述】:

我是 Web 开发的新手,我正在使用 React,但我真的不明白这个错误: 我有一个嵌套在对象“github”内的对象“候选人”,我想显示回购的数量。所以我尝试了console.log(candidate.github.repos),但它给我一个错误说“TypeError:无法读取未定义的属性'repos'”。 但是 console.log(candidate.github) 正在工作并向我展示我的对象!这是我在控制台中得到的:

Github {stars: 0, watchers: 0, forks: 0, issues: 0, size: 0, …}
stars: 0
watchers: 0
forks: 0
issues: 0
size: 0
network: 0
repos: 5
subscribers: 0
_id: "5e859c9876036d0cf33ab457"
candidate: "5df21c4417622d00137f5702"
date: "2020-04-04T10:53:19.894Z"
__proto__: Object

这是我从数据库中获取数据后发送的候选对象:

const github = await GitHub.findOne({candidate: cand._id.toString()});    
const candidateRes = {
        concrete_experience: cand.concrete_experience,
        chronological_experience: Array.from(cand.chronological_experience),
        github
      };
      res.json(candidateRes);

和console.log(typeof(candidate.github)) 发回“对象”...

如果这是一个愚蠢的错误,我很抱歉,但我在这里迷路了......我做错了什么?

非常感谢您的帮助。

【问题讨论】:

  • 你在哪里以及如何在 React 中使用?
  • 您在哪个生命周期方法上调用后端 api 来获取数据?

标签: javascript json reactjs object


【解决方案1】:

我明白我的愚蠢错误。我忘了把 github 对象放在 reducers 中候选对象的 initialState 中,所以在 fetch 有时间给我数据之前它是 null ......但是感谢大家回复我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2012-11-12
    • 2021-08-22
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多