P粉2760641782023-08-15 13:57:52
One way is to write like this:
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); // 在这里数据已经准备好了 }; fetchNote(); }, []);
fetchNote
is an asynchronous function, so it takes some time to complete the task and get the data. Therefore, you should wait for the data to be ready, unfortunately when you use setData(notesData)
immediately after calling fetchNote()
, the data is not ready yet.
Or you can return the data inside the async function and automatically return another promise that resolves to the required data, and then you can update your data:
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); }) }, []);