2016-11-29 16 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別の1つは状態を変更することなく](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

関連する問題