2016-11-29 19 views
1

我想覆蓋在我的Redux狀態是一個數組的特定值。我已經獲得了索引,並且還獲得了新文本的價值。我只是不確定覆蓋以前文本的最佳方式。到目前爲止,這是我的減速器。 UPDATE_LINK是我遇到的問題之一。如何使用redux替換數組中的值?

export function linkList(state = [], action) { 
    switch(action.type) { 
     case 'ADD_LINK': 
      var text = action.text; 
      console.log('Adding link'); 
      console.log(text); 
      return { 
       ...state, 
       links: [text, ...state.links] 
      }; 
     case 'DELETE_LINK': 
      var index = action.index; 
      console.log('Deleting link'); 
      return { 
       ...state, 
       links: [ 
        ...state.links.slice(0, index), 
        ...state.links.slice(index + 1) 
       ], 
      }; 
     case 'UPDATE_LINK': 
      var index = action.index; 
      var newText = action.newText; 
      console.log(action.newText); 
      console.log(action.index); 
      return { 
       ...state, 
       // How do I update text? 
      } 
     default: 
      return state; 
    } 
}; 

export default linkList; 
+0

漂亮的代碼格式化:+1: –

+0

您可以使用相同的刪除邏輯並在其中添加更新的鏈接 – maioman

+0

可能有[Replace array item與另一個沒有變異狀態](http://stackoverflow.com/questions/35362460/replace-array-item-with-another-one-without-mutating-state) –

回答

5

你可以使用Array.protoype.map回到哪裏有合適的和新的條目現有條目,其中指數匹配:

var index = action.index; 
var newText = action.newText; 
return { 
    ...state, 
    links: state.links.map((existingLink, currentIndex) => index === currentIndex ? newText : existingLink) 
} 

或者,下面的現有DELETE_LINK邏輯:

return { 
    ...state, 
    links: [ 
     ...state.links.slice(0, index), 
     newText, 
     ...state.links.slice(index + 1) 
    ], 
}; 
+0

我從來沒有考慮過使用'map' - 很酷的解決方案:) –

+1

您可能還想看看Redux文檔[「Structuring Reducers」](http://redux.js.org/docs/recipes/StructuringReducers.html)部分的一些信息。具體來說,請參閱[「不可更新的更新模式」](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html)頁面。 – markerikson