简体   繁体   English

为什么React UseState返回const数组

[英]Why React useState return const array

I am currently learning React and React hook. 我目前正在学习React和React钩子。 A classic example of using useState is as below: 使用useState的经典示例如下:

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

My question is why the returned array is const? 我的问题是为什么返回的数组是const? I think at least the value of count is changed over time. 我认为至少count的值会随着时间而改变。

The value returned by useState is not a const array, rather its just an array which the user has decided to declare as const . useState返回的值不是const数组,而只是用户已决定声明为const的数组。 Think of the above as 认为以上是

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

So in short, the syntax const [count, setCount] = useState(0); 简而言之,语法const [count, setCount] = useState(0); is an Array destructuring syntax . Array destructuring syntax

Not its is declared as const because you are not reassigning count or setCount to something else in your code, instead just using setCount method to update the state count. 不是将其声明为const因为您没有将countsetCount重新分配给代码中的其他内容,而是仅使用setCount方法更新状态计数。


React authors decided to return an array with state value and state setter so that you can name it anything you want instead of using a pre-decided name while destructuring. React作者决定返回一个带有state valuestate setter的数组,以便您可以在需要时为它命名,而在构造时无需使用预先确定的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM