useState不适用于数组,React Hooks

时间:2019-09-30 02:41:18

标签: javascript reactjs react-hooks

    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 个答案:

答案 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();
    }, []);