使用 React useState Hook 的标准方法如下:
const [count, setCount] = useState(0);
然而,这个const count
变量显然将被重新分配给不同的原始值。
那么为什么变量没有定义为let count
?
使用 React useState Hook 的标准方法如下:
const [count, setCount] = useState(0);
然而,这个const count
变量显然将被重新分配给不同的原始值。
那么为什么变量没有定义为let 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
注意:钩子更复杂,实际上并没有像这样实现。这只是为了展示类似的行为。
调用 setCount 后,组件被重新渲染,并且新的 useState 调用返回新值。关键是 count 是不可变的。所以这里没有错别字。
从技术上讲,它是每次渲染时的新变量。
在这里我发现 const 令人沮丧,因为计数需要改变所以
let [count, setCount] = useState(0)
// simply can't use ++ on either side of count increment given we declare as const [count, setCount]
// instead declaration of var or let [count, setCount] allows simpler code
const increment = () => {
setCount(count++); //const cannot do this only let or var
};
它并没有完全分配一个新值。useState 只是一个状态更新函数。在这里使用 Const 是因为值的变化是由 React 在其他地方管理的。你告诉 React 通过调用 useState 为你管理一些值。