import { useState } from 'react';
const App = () => {
if (true) {
const [count, setCount] = useState(0)
console.log(123)//123
}
const [bool, setBool] = useState(false)
console.log(bool)//false
console.log(count)//count is not defined
return (
<>
</>
);
};
export default App;
因为 hooks 为了在函数组件中引入状态,维护了一个有序表。
这样每次执行才能保证状态能对应上。
比如第一次执行函数组件时,我们拿到状态 count(通过useState,初始值为 0 )和 bool(通过 useState,初始值为 false),它们其实被保存到一个有序表中,它们的值会记录下来: [0, false] 。
第二次执行函数组件, 会 按顺序 从这个表中拿出 0 和false,赋值给 count 和 bool。
如果你把 hook 写到判断条件下,导致某个 useState 不执行了,这里我们假设 count 的 useState 因为判断条件没有执行,会发生什么?结果是 bool 拿到了 0,发生了错位。
函数本身不能保存状态,我们需要额外维护一个有序的表,在执行 useState 之类的 hook 时,将它们保存到这个表里。
这要求每次函数组件的 hook 执行的位置相同,数量正确,否则会导致错位,不能拿到预期的状态值。