我想知道什么样的设计最适合这个.我有一个远程获取的列表.让我们说这是一个帖子列表.
posts {
1: { title: 'some title', body: 'some body'},
2: { title: 'another title', body: 'another body'}
}
Run Code Online (Sandbox Code Playgroud)
在此列表中,用户可以为操作选择每个帖子(甚至是批处理操作).假设在UI中每个小帖子都有一个复选框.
因此,后端并不关心这些选择操作,但我需要确切地知道选择哪些帖子(例如删除),以便前端可以向后端发送请求.处理它的一种方法是使状态的形状如下所示:
{
posts {
1: { title: 'some title', body: 'some body'},
2: { title: 'another title', body: 'another body'}
}
selectedPosts: [1, 2]
}
Run Code Online (Sandbox Code Playgroud)
但这可能会使UI中的渲染变得复杂.
然后另一种方法是在选择帖子时直接修改每个帖子的数据.像这样:
{
posts {
1: { title: 'some title', body: 'some body', selected: true},
2: { title: 'another title', body: 'another body'}
}
}
Run Code Online (Sandbox Code Playgroud)
但这似乎与如何使用反应和还原剂相对立.任何反馈表示赞赏!
我会采用前一种方法,并编写任何类型的助手,将数据按照您需要的方式进行按摩.例如,一个简单的map可以获得所有选定的帖子:
const selectedPosts = state.selectedPosts.map(id => state.posts[id]);
Run Code Online (Sandbox Code Playgroud)
你可以在你的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]);
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
603 次 |
| 最近记录: |