![](/img/trans.png)
[英]Javascript find() array method is returning undefined. what am I doing wrong?
[英]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.