Recoil:设置 atomFamily 时父状态不会更新

问题描述

我有一个订阅了 Recoil atomFamily 的 React 功能组件。意图是 atomFamily 将更新父状态中的一项,然后依赖父状态的另一个组件将通过 useEffect 重新渲染。然而,这似乎并没有发生。为什么会这样?从看起来(以及我自己的实验)使用 Recoil 选择器更改父状态的部分应该会自动传播回父状态。

选择器状态项如下所示:

import { atomFamily,selectorFamily } from "recoil";
import { GroupInterface } from './../interfaces/GroupInterface';
import { GroupList } from './GroupList';

export const GroupSelector = atomFamily({
    key: "GroupSelector",default: selectorFamily({
        key: "GroupSelector/default",get: id => ({get}): GroupInterface => {
            const groupList = get(GroupList);

            return groupList.find((group) => group.id === id) as GroupInterface
        }
    })
})

父状态项如下所示:

import { atom } from 'recoil';
import { GroupInterface } from '../interfaces/GroupInterface';

export const GroupList = atom({
    key: "GroupList",default: [] as GroupInterface[]
})

设置atomFamily后需要更新的组件如下:

useEffect(() => {
    setCurrentActiveSwaps(getCurrentActiveSwaps(groupList));
    // eslint-disable-next-line
},[groupList])

解决方法

首先,您为 GroupSelector 分配了一个 atomFamily,

GroupSelector = atomFamily({

然后该原子的默认值设置为一个 selectorFamily,

 default: selectorFamily({

通常,您会将数组或对象作为默认值。使用 selectorFamily 作为默认值很有趣,但不确定它会导致什么。

这是一个很好的例子,

How to get all elements from an atomFamily in recoil?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...