简体   繁体   English

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

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

I'm trying to display the value of an object within an array of Github repositories (retrieved from a parsed JSON) in my React app but I'm getting an error that the browser can't read property key of undefined.我正在尝试在我的 React 应用程序中显示 Github 存储库数组(从解析的 JSON 中检索)中的对象的值,但我收到一个错误,即浏览器无法读取未定义的属性key

I'm able to console.log the JSON data and the objects within it but if I try to log the values within those objects, I get the error.我能够 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>
)

} }

If I put JSON.stringify(repoList) within the div element, it shows the data.如果我将JSON.stringify(repoList)放在 div 元素中,它会显示数据。

If I put JSON.stringify(repoList[0]) within the div element, it also shows the data.如果我将JSON.stringify(repoList[0])放在 div 元素中,它也会显示数据。

But if I put something like repoList[0].id nothing appears.但是如果我放了类似repoList[0].id东西,什么也不会出现。 This happens with each key listed.列出的每个键都会发生这种情况。 And I can confirm that the key is there.我可以确认钥匙在那里。 What am I doing wrong?我究竟做错了什么?

You're calling async functions to populate the repo list.您正在调用异步函数来填充 repo 列表。 The first time the return tries to use repoList[0].id , there is no repoList[0] .第一次返回尝试使用repoList[0].id ,没有repoList[0] You may want to initialize repoList to a non-error-ing dummy object when you set it up with useState({})当您使用useState({})设置它时,您可能希望将 repoList 初始化为一个不会出错的虚拟对象

Try this.尝试这个。

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

...

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

If your div does not have styles, better user Fragment , it result in better performance.如果你的div没有样式,更好的用户Fragment ,它会导致更好的性能。

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

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