2016-05-17 54 views
0

我想添加immutableJS到Mern.io.當我嘗試從帖子列表中刪除帖子時,將其設置回我的狀態,狀態不會更新。爲什麼我的狀態不會改變使用immutableJS?

case ActionTypes.DELETE_POST : 
    const removeArray = state.get('posts') 
       .filter((post) => post._id !== action.post._id) 
    console.log(removeArray.length) 
    state.set('posts', removeArray) 
    console.log(state) 
    return state; 

在這個例子中,如果我有一個數組5我應該能夠過濾出來,然後再設置新的數組「帖子」。我不明白的是,我可以從數組中刪除對象,removeArray將比state.posts少一個。但是當我控制日誌狀態時它是一樣的。我錯過了什麼?

回答

6

當您撥打state.set(...)時,它會返回一個新對象。原來的state沒有變化。我改變了3個系在你的代碼片段:

case ActionTypes.DELETE_POST : 
    const removeArray = state.get('posts') 
       .filter((post) => post._id !== action.post._id) 
    console.log(removeArray.length) 
    const newState = state.set('posts', removeArray) // assign to another variable 
    console.log(newState) // and log here 
    return newState; // and you'll probably want to return the new state 
+0

這也是情理之中的切換到'state.update(「職位」,...)' – zerkms

+3

這是一種使用Immutable.js整點的:) – RJo

+0

@zerkms感謝您更新代碼段! – franky

相關問題