4

我想知道什么设计最适合这个。我有一个远程获取的列表。假设这是一个帖子列表。

posts  {
    1: { title: 'some title', body: 'some body'},
    2: { title: 'another title', body: 'another body'}
}

在此列表中,用户可以选择每个帖子进行操作(甚至批量操作)。假设在 UI 中每个小帖子都会有一个复选框。

因此,后端并不关心这些选择操作,但我需要确切知道选择了哪些帖子(例如删除),以便前端可以向后端发送请求。处理该问题的一种方法是使状态的形状如下所示:

{
    posts  {
        1: { title: 'some title', body: 'some body'},
        2: { title: 'another title', body: 'another body'}
    }
    selectedPosts: [1, 2]
}

但这可能会使 UI 中的渲染变得复杂。

那么另一种选择是在选择帖子时直接修改每个帖子的数据。像这样:

{
    posts  {
        1: { title: 'some title', body: 'some body', selected: true},
        2: { title: 'another title', body: 'another body'}
    }
}

但这似乎与如何使用 react 和 redux 背道而驰。任何反馈表示赞赏!

4

1 回答 1

6

我会采用前一种方法,并编写您需要的任何类型的助手,将数据按摩成您需要的东西。例如,一个简单的map可以获取所有选定的帖子:

const selectedPosts = state.selectedPosts.map(id => state.posts[id]);

你会在你的connect函数中使用这样的东西,或者使用类似reselect的东西:

import { createSelector } from 'reselect';

const postsSelector = state => state.posts;
const selectedPostIdsSelector = state => state.selectedPosts;

const selectedPostsSelector = createSelector(
  postsSelector ,
  selectedPostIdsSelector ,
  (posts, selectedPosts) => selectedPosts.map(id => posts[id]);
);
于 2015-09-29T03:33:51.870 回答