反应两次获取数据

时间:2021-04-02 16:23:26

标签: reactjs firebase use-effect

我试图从谷歌的 firestore 中的 useEffect 中获取一些数据,并将其保存在 useState 变量中

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1)
    }
    fetchFirst()
}, [])

现在,我想从 firestore 中获取一些其他数据,但此数据需要从先前获取的 (fetchFirst) 数据中获取一些信息。我试图这样做但不起作用

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1)
    }
    const fetchSecond = async (data1) => {
        ...
        // setting the new found data in a useState
        setData2(data2)
    }
    fetchFirst()
    fetchSecond(data1)
}, [])

我的第一次提取完全正常,但是当我的代码到达第二次提取时,输入数据 (data1) 为空。有人可以帮我弄清楚。谢谢

3 个答案:

答案 0 :(得分:1)

两个函数都是async。当 fetchSecond 值更改时,您需要调用 data1

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1)
    }
    fetchFirst()
}, []);


useEffect(() => {
    const fetchSecond = async (data1) => {
        ...
        // setting the new found data in a useState
        setData2(data2)
    }
    fetchSecond(data1)
}, [data1]);

或者在fetchSecond块内调用then

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1);
        return data1 //--> return data value
    }
    const fetchSecond = async (data1) => {
        ...
        // setting the new found data in a useState
        setData2(data2)
    }
    fetchFirst().then(data => fetchSecond(data));
    
}, []);

答案 1 :(得分:1)

如果您使用异步,您应该使用 await 关键字等待第一次提取完成,然后在 fetchSecond 中使用其结果:

useEffect(() => {
  const fetchFirst = async (): SomeData => {
    const data = await fetch(...);
    return data;
  };

  const fetchSecond = async (data: SomeData) => {
    await fetch(...);
  };

  const fetchAllData = async () => {
    const data = await fetchFirst();
    await fetchSecond();
  };

  fetchAllData();
}, []);

答案 2 :(得分:0)

您可以在第一个函数调用中简单地调用第二个函数并传递您在状态中设置的数据,而不是传递状态数据。

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // calling the function with new found data
        fetchSecond(data1)

        // setting the new found data in a useState
        setData1(data1)
    }
    const fetchSecond = async (data1) => {
        ...
        // setting the new found data in a useState
        setData2(data2)
    }
    fetchFirst()
}, [])