Asynchronous useEffect chains in React



我在 React 中使用 Hooks 编写了这段代码:

useEffect(() => {
const runEffect = async () => {
const data = await AsyncFunction();
console.log('async operation')
};
runEffect();
});
useEffect(() => {
console.log('useEffect-1')
});
useEffect(() => {
console.log('useEffect-2')
});

结果是这样的: useEffect-1 useEffect-2 async operation

但是我想等待异步使用效果,然后调用另一个使用效果,即我希望预期的结果是: async operation useEffect-1 useEffect-2

怎么做?

问候

//Add 2 states
const [variable1, setVariable1] = useState(null);
const [variable2, setVariable2] = useState(null);
//Remove this out from useEffect
const runEffect = async () => {
const data = await AsyncFunction();
console.log('async operation');
setVariable1(true); //Something that is not null
};
useEffect(() => {
runEffect();
}, []);
useEffect(() => {
if (variable1) {
console.log('useEffect-1');
setVariable2(true); //Something that is not null
}
}, [variable1]);
useEffect(() => {
if (variable2) {
console.log('useEffect-2');
}
}, [variable2]);

相关内容

  • 没有找到相关文章

最新更新