为什么 React Hook useState 使用 const 而不是 let [英] Why React Hook useState uses const and not let
问题描述
使用 React useState Hook 的标准方法如下:
The standard way to use a React useState Hook is the following:
const [count, setCount] = useState(0);
然而,这个 const count
变量显然会被重新分配给不同的原始值.
However this const count
variable is clearly going to be reassigned to a different primitive value.
为什么变量没有定义为let count
?
Why then is the variable not defined as let count
?
推荐答案
显然将被重新分配给不同的原始值
clearly going to be reassigned to a different primitive value
不是真的.当组件被重新渲染时,函数再次执行,创建一个新的作用域,创建一个新的 count
变量,该变量与之前的变量无关.
Not really. When the component is rerendered, the function is executed again, creating a new scope, creating a new count
variable, which has nothing to do with the previous variable.
示例:
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
注意: Hook 更加复杂,实际上并不是这样实现的.这只是为了演示类似的行为.
Note: Hooks are way more sophisticated and are not actually implemented like this. This is just to demonstrate a similar behavior.
这篇关于为什么 React Hook useState 使用 const 而不是 let的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!