繁体   English   中英

Javascript 说对象值未定义。 我究竟做错了什么?

[英]Javascript saying object value is undefined. What am I doing wrong?

我正在尝试在我的 React 应用程序中显示 Github 存储库数组(从解析的 JSON 中检索)中的对象的值,但我收到一个错误,即浏览器无法读取未定义的属性key

我能够 console.log JSON 数据和其中的对象,但是如果我尝试记录这些对象中的值,我会收到错误消息。

const App = () => {
const [repoList, setRepoList] = useState({});

useEffect(() => {
    fetch("https://example.com/api")
        .then(res => res.json())
        .then(data => setRepoList(data));
});

return (
    <div>{repoList[0].id}</div>
)

}

如果我将JSON.stringify(repoList)放在 div 元素中,它会显示数据。

如果我将JSON.stringify(repoList[0])放在 div 元素中,它也会显示数据。

但是如果我放了类似repoList[0].id东西,什么也不会出现。 列出的每个键都会发生这种情况。 我可以确认钥匙在那里。 我究竟做错了什么?

您正在调用异步函数来填充 repo 列表。 第一次返回尝试使用repoList[0].id ,没有repoList[0] 当您使用useState({})设置它时,您可能希望将 repoList 初始化为一个不会出错的虚拟对象

尝试这个。

const [repoList, setRepoList] = useState([]); // Change to array not object.

...

return repoList.length ?
  (<React.Fragment>{repoList[0].id}</React.Fragment>) 
  : (<span>Loading ....</span>)

如果你的div没有样式,更好的用户Fragment ,它会导致更好的性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM