javascript - return new state, don't mutate it. Am i doing it right way? -


i rendering tablist, onclick of tab highlighted. achieving checking selected attribute. everytime tab clicked changing selected true/false in reducer.

mytabsreducer should not mutate return new array.

am doing right way? per documentation should not mutate state (should not alter state). in case i'm altering reducer. ok or there other way achieve it?

export const mytabsreducer = (id) => {       return [         {             id: 1,             name:"my tab 1",             selected: id==1?true:false           },           {             id: 2,             name:"my tab 2",             selected: id==2?true:false           },           {             id: 3,             name:"my tab 3",             selected: id==3?true:false           }       ]     }  const myactivetabreducer = (state = {}, action) => {     switch (action.type) {     case select_plan_tab:       return action.payload     default:       return 1;   } }  const allreducers = (state = {}, action) => {     return {       alltabs: mytabsreducer(myactivetabreducer(state, action)),   } } 

it better have state in way:

const initialstate = {   tabs: [     { id: 1, name: 'tab 1' },     { id: 2, name: 'tab 2' }   ],   selectedtab: 1 } 

so reducer changes selectedtab property on "select_plan_tab":

const activetabreducer = (state = initialstate, action) => {   switch (action.type) {     case select_plan_tab:       return {         ...state,         selectedtab: action.payload       };     default:       return state;   } } 

then, if need tabs array selected property each tab, use selector: see http://redux.js.org/docs/recipes/computingderiveddata.html


Comments