2016-11-29 69 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