开发者问题收集

useState 不适用于数组、React Hooks

2019-09-30
1604
    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 不起作用,数据正在传入。

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();
    }, []);
kyun
2019-09-30