一種方法是這樣寫:
useEffect(() => { let notesData = []; const fetchNote = async () => { const response = await fetch('https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json'); const data = await response.json(); for (const key in data) { notesData.push({ id: key, title: data[key].title, note: data[key].note }); } setData(notesData); // 在這里數(shù)據(jù)已經(jīng)準(zhǔn)備好了 }; fetchNote(); }, []);
fetchNote
是一個(gè)異步函數(shù),所以它需要一些時(shí)間來完成任務(wù)并獲取數(shù)據(jù)。因此,你應(yīng)該等待數(shù)據(jù)準(zhǔn)備好,不幸的是,當(dāng)你在調(diào)用 fetchNote()
后立即使用 setData(notesData)
時(shí),數(shù)據(jù)還沒有準(zhǔn)備好。
或者你可以在異步函數(shù)內(nèi)部返回?cái)?shù)據(jù),并自動(dòng)返回另一個(gè)解析為所需數(shù)據(jù)的 promise,然后你可以更新你的數(shù)據(jù):
useEffect(() => { let notesData = []; const fetchNote = async () => { const response = await fetch('https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json'); const data = await response.json(); for (const key in data) { notesData.push({ id: key, title: data[key].title, note: data[key].note }); } return notesData; // 返回一個(gè)解析為 'notesData' 的 promise }; fetchNote() .then((updatedData) => { setData(updatedData); }) }, []);