首页 > 解决方案 > 嵌套对象在尝试访问其属性时变得未定义

问题描述

我是 Web 开发的新手,我正在使用 React,但我真的不明白这个错误:我有一个对象“candidate”,嵌套在一个对象“github”中,我想显示 repos 的数量。所以我尝试了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

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

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)) 发回“对象”...

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

非常感谢您的帮助。

标签: javascriptjsonreactjsobject

解决方案


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


推荐阅读