为什么 React useState return 常量数组

Why React useState return const array

我目前正在学习 React 和 React hook。一个使用useState的经典例子如下:

const [count, setCount] = useState(0);

我的问题是为什么返回的数组是常量?我认为至少count的值是随时间变化的。

useState 编辑的值 return 不是常量数组,而只是用户决定声明为 const 的数组。将以上视为

const stateValue = useState(0);
const count = stateValue[0];
const setCount = stateValue[1];

所以简而言之,语法 const [count, setCount] = useState(0); 是一个 Array destructuring syntax

它没有被声明为 const 因为您没有将 countsetCount 重新分配给代码中的其他内容,而只是使用 setCount 方法更新状态计数。


React 作者决定 return 一个带有 state valuestate setter 的数组,这样你就可以随意命名它,而不是在解构时使用预先确定的名称。