2017-08-11 115 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

非常感謝。我會給它一個鏡頭,讓你知道我如何繼續。我也讓我的問題更清楚一點。那個更好嗎?你有什麼可能需要更清晰的建議嗎? –

相關問題