reactjs 我得到一个错误:效果回调是同步的,以防止竞争条件,我无法按照它想要的方式格式化它

nwo49xxi  于 2023-06-05  发布在  React
关注(0)|答案(2)|浏览(239)

我得到了这个错误,虽然这个相同的格式似乎在例子中工作。

const response = await axios.get('http://localhost:5000/get-tasks')

    const dataObject = response.data
    

    const arrayOfKeys = Object.keys(dataObject)
    const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])

    console.log(arrayOfKeys)
    console.log(arrayOfData)
  }, [])```
9bfwbjaz

9bfwbjaz1#

useEffect函数arg不能是异步的,但是你可以在里面调用一个async函数。

useEffect(() => {
  async function getTasks() {
    const response = await axios.get('http://localhost:5000/get-tasks')

    const dataObject = response.data

    const arrayOfKeys = Object.keys(dataObject)
    const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])

    console.log(arrayOfKeys)
    console.log(arrayOfData)
  };

  getTasks();
}, []);
li9yvcax

li9yvcax2#

async函数返回Promise,而useEffect不期望返回Promise。(如果有任何返回,它应该是卸载组件时用于清除任何效果的函数。)
如果你想在useEffect中使用async/await,那么你可以把整个东西 Package 在一个async IIFE中。例如:

useEffect(() => {
  (async () => {
    const response = await axios.get('http://localhost:5000/get-tasks');
    const dataObject = response.data;

    const arrayOfKeys = Object.keys(dataObject);
    const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key]);

    console.log(arrayOfKeys);
    console.log(arrayOfData);
  })();
}, []);

或者,您可以在内部async操作中使用.then(),而不是await

useEffect(() => {
  axios.get('http://localhost:5000/get-tasks').then(response => {
    const dataObject = response.data;

    const arrayOfKeys = Object.keys(dataObject);
    const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key]);

    console.log(arrayOfKeys);
    console.log(arrayOfData);
  });
}, []);

相关问题