React中的异步useEffect链

时间:2019-09-19 08:28:05

标签: javascript reactjs react-native react-hooks

我已经在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

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

怎么办?

致谢

1 个答案:

答案 0 :(得分:1)

//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]);