简体   繁体   English

为什么useState变量`const`在反应?

[英]Why are useState variables `const` in react?

My understanding is, when using useState() , we should declare the array as such:我的理解是,在使用useState()时,我们应该这样声明数组:

const [someBooleanValue, setSomeBooleanValue] = useState(false)

Instead of代替

let [someBooleanValue, setSomeBooleanValue] = useState(false)

Normally, const is used on variables that won't be changing.通常, const用于不会改变的变量。 Here, someBooleanValue will be changing.在这里, someBooleanValue将发生变化。 What is going on that allows us to use the const keyword in this case?在这种情况下,发生了什么让我们可以使用const关键字?

In React Hooks with a Functional Component, your code gets a single value of state for each call into your functional component.在带有功能组件的React Hooks 中,您的代码为每次调用功能组件获取一个状态值。 React handles the storage separately and returns that current value via useState on each execution of your code, providing the latest state value. React 单独处理存储并在每次执行代码时通过useState返回当前值,提供最新的状态值。

From the docs:从文档:

We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function.我们声明了一个名为 count 的状态变量,并将其设置为0。React 将记住它在重新渲染之间的当前值,并将最新的值提供给我们的函数。 If we want to update the current count, we can call setCount.如果我们想更新当前计数,我们可以调用 setCount。

So in this case, we use const because the value should never be reassigned in our code.所以在这种情况下,我们使用const是因为在我们的代码中永远不应该重新分配该值。

In the functional component, we declare the state using const.在功能组件中,我们使用 const 声明 state。 To update the state we have to go through a specific method that uses the Set function.要更新 state,我们必须通过使用 Set function 的特定方法来更新 go。 It is completely fine to change the state by using the Set process.使用 Set 过程更改 state 完全没问题。

We use const to avoid reassignment of state.我们使用 const 来避免重新分配 state。 That's shit!!!那是狗屎!!!

const [someBooleanValue, setSomeBooleanValue] = useState(false)

is actually something like this实际上是这样的

const handleState = useState(false)

handleState[0] is someBooleanValue and handleState[1] is setSomeBooleanValue . handleState[0]someBooleanValue并且handleState[1]setSomeBooleanValue

This handleState is an array, which is a reference type.这个handleState是一个数组,是一个引用类型。 The handleState is just a pointer to that array and this pointer actually never changes. handleState只是一个指向该数组的指针,这个指针实际上永远不会改变。

someBooleanValue and setSomeBooleanValue are elements of the handleState array at index 0 and 1 . someBooleanValuesetSomeBooleanValuehandleState数组在索引01处的元素。

So, someBooleanValue changes, not the pointer to the array in which it is contained.因此, someBooleanValue发生了变化,而不是指向包含它的数组的指针。

Hope this clarifies!希望这能澄清!

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

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