atomFamily 在反冲中的用例是什么?

What is the use case of atomFamily in recoil?

我做了我的第一个反冲实验,建立了一个 editable table。每个单元格都有一个原子,用于存储其行、列和文本值。 我构建它的方式是

  1. 将每个单元格的原子初始化为字典(只是一个普通对象),键的格式为 [column]x[row]
  2. 然后我在 Table 组件中迭代这些键,并只将键传递给每个 Cell 组件
  3. Cell 组件使用 useRecoilState 并通过使用它作为 prop 传递的密钥访问主字典来找到它的特定 Atom。

现在,在我看来,这个用例(创建数千个具有相同形状的相关原子)是 atomFamily 的目的,但我不明白如何使用它这样,您就可以用特定值初始化每个原子。

而且,除此之外,我不明白使用 atomFamily 比存储原子集合有什么优势。我知道涉及记忆,但我不明白什么被记忆了,如果我没看错的话,通过使用相同的 id 再次调用函数来召回特定原子的能力,这会让你几乎我用字典得到的行为相同。

区别很小:如果您想手动记忆和管理自己的 atom 集合,那么您当然可以。 atomFamily 本质上只是 sugar for that: it handles the memoization for you, so all that you have to do is use a unique key to access each atom. Verbatim from the documentation for atomFamily:

An atom represents a piece of state with Recoil. An atom is created and registered per <RecoilRoot> by your app. But, what if your state isn’t global? What if your state is associated with a particular instance of a control, or with a particular element? For example, maybe your app is a UI prototyping tool where the user can dynamically add elements and each element has state, such as its position. Ideally, each element would get its own atom of state. You could implement this yourself via a memoization pattern. But, Recoil provides this pattern for you with the atomFamily() utility. An Atom Family represents a collection of atoms. When you call atomFamily() it will return a function which provides the RecoilState atom based on the parameters you pass in.


至于如何使用 atomFamily 的示例:除了上面链接的文档之外,还有 lots of existing questions and answers on Stack Overflow which already cover exactly that。这是我之前回答过的几个: