微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。