渲染后由于第一个useState会发生什么?执行会立即从第二个useState开始吗?
import React, { useState, useEffect } from 'react';
const [var1, setVar1] = useState();
const [var2, setVar2] = useState();
...
useEffect(() => {
if (var1) {
setVar2('abc')
setVar1('zyx')
}
}, [var1]);
答案 0 :(得分: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