2017-08-11 140 views
-1

根据Redux docs,规范化状态是处理前端数据结构的最佳方法。他们给出的例子如下:将Redux减速器映射到状态中的未知密钥

{ 
    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"] 
    } 
} 

一个如何去这样的帖子或评论的ID,可以动态地设置为关键写作减速。

回答

1

我不知道(因为这个问题不是很清楚),但我想你想返回一个新的对象从字面减速时使用计算属性名称:

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 
     ) 
    }; 
} 
+0

感谢您的答复。如果状态正在初始化并且没有任何操作被分派,会发生什么?我会做一些检查,如果它不存在,如果它不返回一个空的对象,而不是进一步的减速器? –

+1

然后你不想执行这段代码。你必须提供某种安全措施,如“if(!action ||!action.projectName){return state; }''。我修改了我的答案,将其考虑在内。 – mdziekon

+0

非常感谢。我会给它一个镜头,让你知道我如何继续。我也让我的问题更清楚一点。那个更好吗?你有什么可能需要更清晰的建议吗? –

相关问题