【问题标题】:Is there a proven way to manage a collection of atoms in Recoil?有没有一种行之有效的方法来管理 Recoil 中的原子集合?
【发布时间】:2021-07-22 02:24:07
【问题描述】:

我正在测试 Recoil,我需要管理要在主页上显示的帖子列表。

我的第一个想法是把所有帖子都做一个大Atom,但这似乎有点暴力,因为我们可以直接在主页上编辑帖子。

我的第二个想法是动态生成带有前缀的原子:

const onePost = (postId: string) => atom({
  key: 'post_' + postId,
  default: null,
  effects_UNSTABLE: [localStorageEffect('@post_' + postId)],
});

然后我意识到我是一个在玩火的菜鸟,我会在 StackOverflow 上询问了解 Recoil 的人......

【问题讨论】:

    标签: reactjs react-native react-state-management recoiljs


    【解决方案1】:

    你可以只使用一个数组:

    const postIds = atom({
      key: 'postIds',
      default: [],
      effects_UNSTABLE: [localStorageEffect('postIds')],
    });
    

    这样,您可以在一个 atom 中管理 id 列表,这些 id 可以引用保存帖子内容数据的不同 atomFamilys。

    【讨论】:

      【解决方案2】:

      您可以使用 atomFamily 来管理您的帖子。如果要添加和删除帖子,可以使用另一个 atom 来管理帖子 ID。

      const postsFamily = atomFamily({
        key: 'postsFamilyKey',
        default: [0, 0],
      });
      
      function PostListItem({postID}) {
        const post = useRecoilValue(postsFamily(postID));
        return (
          <div>
            Post ID: {postID}
            Post: {post}
          </div>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        • 2011-11-08
        • 2018-01-27
        • 1970-01-01
        相关资源
        最近更新 更多