React Hooks,重新渲染 &保持相同的状态 - 它是如何工作的? [英] React Hooks, rerender & keeping same state - how it works underhood?

查看:113
本文介绍了React Hooks,重新渲染 &保持相同的状态 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重新渲染后的以下函数如何保持当前值?

How is it possible that following function after rerender keeps the current value?

const Example = () => {
  const [count, setCount] = useState(0);
  return <button onClick={()=>setCount(count+1)} >{count}</button>
}

逻辑上看:

  1. 初始渲染 = 我们用一个参数调用 useState
  2. rerender = 我们用一个参数再次调用 useState

将组件视为一个干净的功能,这应该可行.但据我了解,useState 将纯组件变成了不纯组件.

Looking at the component as a clean function, this should work. But as I understand it, useState changes pure component into impure component.

但这仍然不能解释在没有自己上下文的箭头函数中实现这种机制.如果 useState 没有挂接到父函数(如唯一 ID、this、回调等),则它不应该知道它在连续的哪个时间被调用.

But this still doesn't explain implementation of such a mechanism in an arrow function that does not have its own context. useState doesn't supposed to know which time in a row it's being called, if it's not hooked to parent function (like unique ID, this, callback, etc.)

React Hooks 看起来打破了函数式编程的许多范式...

React Hooks look like they break many paradigms of functional programming...

推荐答案

在内部 useState 会跟踪他是否第一次使用变量启动钩子.如果它是对 useState 的第一次调用,它会使用传递的参数,否则它会维护自己的 dispatchQueue 用于更新.

Internally useState keeps a track of whether the hooks is being initiated for he first time or not using a variable. If Its the first call to useState it makes use of the passed argument else it maintains its own dispatchQueue which it uses for updates.

就以下声明而言

<button onClick={()=>setCount(count+1)} >{count}</button>

这里不是 setCount 保留变量,而是箭头函数从封闭范围继承了 count 变量.

here its not setCount that is preserving the variable, instead the arrow function inherits the count variable from the enclosing scope.

然而,来自 useState 钩子的 setter 也指定了一个回调方法,它将当前值传递给它.例如

However, the setter from useState hook does also specify a callback method to which it passes the current value. For example

<button onClick={()=>setCount(savedCount => savedCount+1)} >{count}</button>

这里 savedCount 正在从 setCount 传递给回调方法,并在内部反应保持钩子的当前状态.

Here savedCount is being passed from setCount to callback method and react internally maintains the current state of the hook.

这篇关于React Hooks,重新渲染 &amp;保持相同的状态 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆