Redux状态形状没有数据重复

时间:2017-08-20 14:51:45

标签: redux

我是redux的新手,如果我需要更新数据,很难掌握如何在不重复数据的情况下实现良好的状态,并且天真的方式是在几个地方进行更新,但是这将否定单一的事实来源。

我们从API服务器获取用户个人资料和帖子:

www.api.com/users/placeholder { "user": { "username": "placeholder", "bio": "It's my bio", "profileImage": "http://via.placeholder.com/350x150", "isViewerFollowing": false } } www.api.com/posts?author=placeholder { "posts":[{ "id": "1", "caption":"caption placeholder", "image":"http://via.placeholder.com/1000x1000", "createdAt": "2017-08-18T03:22:56.637Z", "updatedAt": "2016-08-18T03:48:35.824Z", "isLikedbyViewer": false, "likesCount": 0, "author": { "username": "placeholder", "bio": "It's my bio", "profileImage": "http://via.placeholder.com/350x150", "isViewerFollowing": false, } }, { "id": "2", "caption":"caption placeholder", "image":"http://via.placeholder.com/1000x1000", "createdAt": "2017-08-18T03:22:56.637Z", "updatedAt": "2016-08-18T03:48:35.824Z", "isViewerLiked": false, "likesCount": 0, "author": { "username": "placeholder", "bio": "It's my bio", "profileImage": "http://via.placeholder.com/350x150", "isViewerFollowing": false, } }], "postsCount": 2 }

例如,我们为用户和帖子设置了单独的缩减器,并且用户想要关注用户/作者,然后我们需要更新两个缩减器中的信息。所以我的最后一个问题是,有人会暗示我在这个特定的例子中看起来状态好吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你应该规范你的Redux状态:你应该保存authorId,而不是为每个帖子保存整个作者对象。

由于您确保在Redux状态的posts分支中有post对象时,您还在authors分支中拥有相关作者,以使用其作者的数据检索所有帖子你可以创建一个选择器:

export function getPosts(reduxState) {
  return reduxState.posts.map(post => {
    const author = reduxState.authors.find(a => a.id === post.authorId);
    return {
      ...post,
      author
    };
  });
}