以下是使用React useState Hook的标准方法:
const [count, setCount] = useState(0);
但是,const count显然要将此变量重新分配给其他原始值。
const count
为什么变量没有定义为let count?
let count
显然将被重新分配给其他原始值
并不是的。重新呈现组件后,将再次执行该函数,从而创建新的作用域,创建新的count变量,该变量与先前的变量无关。
count
例:
let _state; let _initialized = false; function useState(initialValue) { if (!_initialized) { _state = initialValue; _initialized = true; } return [_state, v => _state = v]; } function Component() { const [count, setCount] = useState(0); console.log(count); setCount(count + 1); } Component(); Component(); // in reality `setCount` somehow triggers a rerender, calling Component again Component(); // another rerender
注意: 挂钩更为复杂,实际上并未像这样实现。这只是为了演示类似的行为。