const [News, setNews] = useState([]);
useEffect(() => {
async function fetchData() {
const result = await database.collection('newslatters').get();
result.docs.forEach(doc =>
setNews([...News, { id: doc.id, data: doc.data() }])
);
console.log(News); //empty array
}
fetchData();
}, []);
我正在从Firestore获取数据,但是setState无法正常工作,数据即将到来。
答案 0 :(得分:1)
尝试一下。
//const [News, setNews] = useState([]); // you'd better use lowercase.
const [news, setNews] = useState([]);
useEffect(() => {
async function fetchData() {
const result = await database.collection('newslatters').get();
/* result.docs.forEach(doc =>
setNews([...News, {
id: doc.id,
data: doc.data()
}])
); */
let temp = [];
result.docs.forEach(doc => temp.push({id: doc.id, data: doc.data() });
setNews(temp);
// console.log(news); //empty array
}
fetchData();
}, []);