如何获取数据,然后使用useEffect(React JS)在加载时异步执行其他任务

时间:2020-11-06 16:34:34

标签: javascript reactjs react-hooks fetch

我正在努力弄清楚如何执行此操作:

const [stateOne, setStateOne] = useState();
const [stateTwo, setStateTwo] = useState();

useEffect(() => {
  /* fetch data */

  setStateOne(); /* not before data is fetched */
  setStateTwo(); /* not before data is fetched and setStateOne is complete */
},[])

从概念上讲这是正确的,并且可以在useEffect中异步运行此类任务吗?

4 个答案:

答案 0 :(得分:1)

多种效果:

const [asyncA,setAsyncA] = useState();
const [asyncB,setAsyncB] = useState();


useEffect(() => {

  (async() => {
     setAsyncA(await apiCall());
  })();

 // on mount fetch your data - no dependencies
},[]);


useEffect(() => {
  if(!asyncA) return;
  
  (async() => {
     setAsyncB(await apiCall(asyncA));
  })();

  // when asyncA is ready, then get asyncB
},[asyncA]);

useEffect(() => {
  if(!asyncA || !asyncB) return;
  // both are ready, do something
},[asyncA,asyncB])


OR,只是一种异步功能,具有一种效果:

useEffect(() => {

  (async() => {
     const first = await apiCallA();
     const second = await apiCallB(first);
  })();

},[]);

答案 1 :(得分:1)

您无法在react挂钩中运行async个动作,因此您需要在挂钩之外提取功能,然后在挂钩内调用它,然后创建第二个effect在{ {1}}已更新为更新状态2。

stateOne

答案 2 :(得分:0)

这将使您了解如何使用useEffect

const {useState, useEffect} = React;

const App = () => {
    const [stateOne, setStateOne] = useState(null)
    const [stateTwo, setStateTwo] = useState(null)

    useEffect(() => {
       stateOne && call(setStateTwo); 
    },[stateOne])
    
    const call = setState => {
      let called = new Promise(resolve => {
        setTimeout(() => {
          resolve(true)
        }, 2000)
      })
      called.then(res => setState(res))
    }
    
    return (
      <div>
        <button onClick={() => call(setStateOne)}>make call</button>
        <pre>stateOne: {JSON.stringify(stateOne)}</pre>
        <pre>stateTwo: {JSON.stringify(stateTwo)}</pre>
      </div>
    )  
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

答案 3 :(得分:-1)

通过直接箭头功能使用async / await

useEffect(() => {
  (async() => {
    /* fetch data */
   // await is holding process till you data is fetched
   const data = await fetchData()
   // then set data on state one
   await setStateOne(); 
   // then set data on state second
   setStateTwo(); 
  })();
},[])