我很难弄清楚如何执行以下操作:
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中异步运行这样的任务是可能的吗?
多重效果:
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])
或者,只有一个异步函数:
useEffect(() => {
(async() => {
const first = await apiCallA();
const second = await apiCallB(first);
})();
},[]);
您不能在react钩子中运行async
操作,因此您需要在钩子外提取功能,然后在钩子内调用它,然后在stateOne
更新为更新状态2后创建第二个运行的effect
。
const fetchAction = async () => {
await fetchData(...)/* fetch data */
setStateOne(); /* not before data is fetched */
}
useEffect(() => {
},[])
useEffect(() => {
setStateTwo();
},[StateOne])
这将使您了解如何使用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>
将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();
})();
},[])