简体   繁体   English

React 的 useState 是如何改变常量的值的?

[英]How does React's useState change the value of a constant?

This is the syntax I'm working with.这是我正在使用的语法。

const [count, setCount] = useState(0);
const handleIncrement = () => {
    setCount((count + 1));
  };

I understand that setCount is creating an instance of count, but I'm really not grasping how exactly count is being changed if it's a constant or how, if it's an instance, it's able to be called and return the most recent value.我知道 setCount 正在创建一个计数实例,但我真的不明白如果计数是一个常量,它究竟是如何改变的,或者如果它是一个实例,它是如何被调用并返回最新值的。

Wouldn't every time React re-renders the page, it reads the constant count first?每次 React 重新渲染页面时,它不会先读取常量计数吗?

It's working just fine for me, but I can't wrap my head around why.它对我来说工作得很好,但我无法理解为什么。

count is 'constant' for the duration of the function. When setCount() is called, the local count doesn't change.在 function 的持续时间内, count是“常数”。调用setCount()时,本地count不会改变。 Eventually your component gets rendered again with the new value.最终,您的组件将使用新值再次呈现。

During this new render the count is updated, but it will again be constant for the duration of the render/function.在此新渲染期间, count会更新,但在渲染/函数期间它将再次保持不变。

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

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