【问题标题】:redux react strategy with async data and interactionredux 对异步数据和交互的反应策略
【发布时间】:2015-12-26 07:59:43
【问题描述】:

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

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 的使用方式背道而驰。任何反馈表示赞赏!

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    我会采用前一种方法,并编写您需要的任何类型的帮助程序,以将数据处理成您需要的内容。例如,一个简单的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]);
    );
    

    【讨论】:

    • 很好的答案,但重新选择的 api 很难消化。
    • 感谢您的确认!
    • @RickJolly 您不必使用 Reselect API 来编写获取状态并返回 state-ready-for-UI-components 的函数。请参阅 Redux example in Flux Comparison 了解甚至不使用 Reselect 的选择器。
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2015-08-05
    相关资源
    最近更新 更多