首页 > 解决方案 > 具有不可变的 Redux 减速器

问题描述

我想将一个帖子添加到减速器中的一组帖子中。通常我会这样做:

CREATE_NEW__POST_SUCCESS: {
    return {
        ...state,
        fetchingPosts: false,
        error: null,
        posts: [...state.posts, ...action.payload],
        };

但是我当前的项目要求我使用 Immutable.js 和 Immutable 状态设置为 .set() 或 .merge() 或 .update()

case CREATE_NEW_POST_SUCCESS: {
    return state
        .set('fetchingPosts', false)
        .set('posts', action.payload)
        .set('postsError', null);

这会用一个帖子对象覆盖整个帖子数组。我尝试了很多东西,比如

 .set('posts' ,[...state.posts, ...action.payload])

但没有快乐

标签: javascriptreactjsreact-reduxredux-sagaimmutable.js

解决方案


您可以使用updateIn类似于此处的答案。

case CREATE_NEW_POST_SUCCESS: {
    return state
        .set('fetchingPosts', false)
        .updateIn(['posts'], posts => posts.push(action.payload))
        .set('postsError', null);

推荐阅读