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 获取数据,但设置状态它不起作用,数据即将到来。
试试这个。
//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();
}, []);