useEffect中的多个useState,执行顺序

时间:2019-12-19 14:09:56

标签: reactjs react-hooks

渲染后由于第一个useState会发生什么?执行会立即从第二个useState开始吗?

   import React, { useState, useEffect } from 'react';
    const [var1, setVar1] = useState();
    const [var2, setVar2] = useState();
    ...
    useEffect(() => {
        if (var1) {
          setVar2('abc')
          setVar1('zyx')
        }
    }, [var1]);

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题:

useEffect在渲染之后运行。因此执行将是:

  • useState 1
  • useState 2
  • 返回
  • useEffect(仅在依赖项更改时运行)
  • 重新渲染

在您的useEffect中,setVar2设置器将在第一个设置器之前调用。但是请记住,设置状态是异步的,因此第一次执行并不意味着首先完成。

要回答关于效果内执行顺序的更具体的问题,请考虑示例中的控制台日志:

const TestEffect= (props) => {
  const [test, setTest] = React.useState();
  const [test2, setTest2] = React.useState();

  React.useEffect(() => {
    console.log('effect was called')

    setTest2('test2');
    console.log('set test 2 called')

    setTest('test');
    console.log('set test 1 called')
  }, [test])

  console.log('render')
  return <div>Test</div>;
}

// Output:

// render
// effect was called
// set test 2 called
// set test 1 called
// render
// effect was called
// set test 2 called
// set test 1 called
// render