React 如何实现 hooks 使其依赖调用顺序 [英] How does React implement hooks so that they rely on call order

查看:88
本文介绍了React 如何实现 hooks 使其依赖调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React Hooks useState 可以将本地状态附加到无状态功能组件,例如

the React Hooks useState can attach local state to stateless functional component, for instance

const [name, setName] = useState('tom')
const [age, setAge] = useState(25)

我想知道执行上面两行后本地状态对象树是什么样子的?钩子规则说明了如何处理状态

I am wondering how the local state object tree looks like after executing the two line above? Rules of Hooks says something about how state is handled

React 依赖于调用 Hook 的顺序

React relies on the order in which Hooks are called

或者本地状态根本就不是对象树,只是一个数组?

Or the local state is not object tree at all, just an array?

提前致谢!

推荐答案

钩子在内部实现为一个队列,每个钩子由一个节点表示,该节点具有对下一个的引用.

Hooks internally are implemented as a queue with each hook being represented by a node having the reference to the next one.

来自文档:

有一个内部的记忆单元"列表与每个成分.它们只是我们可以放置一些数据的 JavaScript 对象.当您调用像 useState() 这样的 Hook 时,它会读取当前单元格(或在第一次渲染期间初始化它),然后将指针移动到下一个.这是多个 useState() 调用每个 get 的方式独立的本地状态.

There is an internal list of "memory cells" associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

架构类似于

{
  memoizedState: 'A',
  next: {
    memoizedState: 'B',
    next: {
      memoizedState: 'C',
      next: null
    }
  }
}

单个钩子的架构如下.它可以在 一个>

The schema of a single hook is as below. It can be found in the implementation

function createHook(): Hook {
  return {
    memoizedState: null,

    baseState: null,
    queue: null,
    baseUpdate: null,

    next: null,
  };
}

让钩子按照它们的方式运行的关键属性是 memoizedStatenext.

The key properties that let hooks behave the way they are are memoizedState and next.

在每个函数组件调用之前,将调用 prepareHooks(),其中当前光纤及其在钩子队列中的第一个钩子节点将存储在全局变量中.这样,每当我们调用钩子函数 (useXXX()) 时,它都会知道在哪个上下文中运行.

Before each and every function Component invocation, prepareHooks() is gonna be called, where the current fiber and its first hook node in the hooks queue are gonna be stored in global variables. This way, any time we call a hook function (useXXX()) it would know in which context to run.

更新后 finishHooks() 将被调用,其中钩子队列中第一个节点的引用将存储在渲染纤程的 memoizedState 属性中

After the update finishHooks() will be called, where a reference for the first node in the hooks queue will be stored on the rendered fiber in the memoizedState property

这篇关于React 如何实现 hooks 使其依赖调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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