将 Redux reducer 映射到 State 中的未知键

Mapping Redux reducers to unknown keys in State

根据 Redux docs,规范化状态是在前端处理数据结构的最佳方式。他们给出的例子如下:

{
  posts : {
    byId : {
        "post1" : {
            id : "post1",
            author : "user1",
            body : "......",
            comments : ["comment1", "comment2"]    
        },
        "post2" : {
            id : "post2",
            author : "user2",
            body : "......",
            comments : ["comment3", "comment4", "comment5"]    
        }
    },
    allIds : ["post1", "post2"]
  },
  comments : {
    byId : {
        "comment1" : {
            id : "comment1",
            author : "user2",
            comment : ".....",
        },
        "comment2" : {
            id : "comment2",
            author : "user3",
            comment : ".....",
        },
        "comment5" : {
            id : "comment5",
            author : "user3",
            comment : ".....",
        },
    },
    allIds : ["comment1", "comment2", "comment5"]
  }
}

如何以 post 或评论的 id 可以动态设置为键的方式编写 reducer。

我不确定(因为问题不是很清楚),但我认为您想在从 reducer 返回新对象文字时使用计算的 属性 名称:

projectsReducers (state={}, action) {
    // Ensure that the projectName is actually accessible
    if (!action || !action.projectName) {
        return state;
    }

    // Retrieve the project name dynamically
    const projectName = action.projectName;

    return {
        // Preserve the previous state by spreading all of it's properties
        // please note that Object spread is still a Stage 3 proposal for ECMAScript,
        // so transpilation might be required
        ...state,

        // Assign current project's new state
        [projectName]: singleProjectReducer(
            state[projectName],
            action
        )
    };
}