Salah satu cara ialah menulis seperti ini:
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)準備好了 }; fetchNote(); }, []);
fetchNote
是一個異步函數(shù),所以它需要一些時間來完成任務(wù)并獲取數(shù)據(jù)。因此,你應(yīng)該等待數(shù)據(jù)準備好,不幸的是,當你在調(diào)用 fetchNote()
后立即使用 setData(notesData)
Data belum siap lagi.
Sebagai alternatif anda boleh mengembalikan data di dalam fungsi async dan secara automatik mengembalikan janji lain yang menyelesaikan kepada data yang diperlukan, dan kemudian anda boleh mengemas kini data anda:
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; // 返回一個解析為 'notesData' 的 promise }; fetchNote() .then((updatedData) => { setData(updatedData); }) }, []);