该钩的规则要求,同样的挂钩,并在同一顺序呼吁每一个渲染。并且有一个关于如果您违反此规则会出问题的解释。例如此代码:
function App() {
console.log('render');
const [flag, setFlag] = useState(true);
const [first] = useState('first');
console.log('first is', first);
if (flag) {
const [second] = useState('second');
console.log('second is', second);
}
const [third] = useState('third');
console.log('third is', third);
useEffect(() => setFlag(false), []);
return null;
}
Run Code Online (Sandbox Code Playgroud)
输出到控制台
render
first is first
second is second
third is third
render
first is first
third is second
Run Code Online (Sandbox Code Playgroud)
并导致警告或错误。
但是,在元素生命周期中不会改变的条件又如何呢?
const DEBUG = true;
function TestConst() {
if (DEBUG) {
useEffect(() => console.log('rendered'));
}
return <span>test</span>; …Run Code Online (Sandbox Code Playgroud)