javascript - Redux state changes but shouldn't -


i have problem. have simple grid , grid gets data redux state. when sort, noticed data changes in state, shouldn't or missunderstood redux @ point. here bit of code

reducer:

const gridoptions = {  columns: ["id", "name", "lastname"],  data: [   {id: 1, name: "test", lastname: "test2"},   {id: 2, name: "test1", lastname: "test3"}  ],  sortby: {},  filter: {} }  const rootreducer = combinereducers({  data: function (state = gridoptions.data, action) {   return [...state];  },  selectedrow: function (state = {}, action) {   switch (action.type) {    case "row_selected":      return action.data    default:     return state  } }, sortby: function (state = gridoptions.sortby, action) { switch (action.type) {   case "sort_change":     return object.assign({}, action.column);   default:     return state;  } }, columns: function (state = gridoptions.columns, action) {  return state; }, filter: function (state = gridoptions.filter, action) {   return state;  } })  const store = createstore(rootreducer); 

the container component. know bit messy.

var mapstatetoprops = (state) => { return {   data: (() => {    if (!state.sortby) {     return state.data    } else {     return state.data.sort()    }   })(),   selectedrow: state.selectedrow,   sortby: state.sortby  }  }  var mapdispatchtoprops = (dispatch) => {  return {   onrowselected: data => dispatch({type: "row_selected", data}),   onsortchange: column => {     dispatch({type: "sort_change", column})   },   onfilter: filtertext => {     dispatch({type: "filter_change", filtertext})   }  } } 

so question. reason don't understand ... if console.log state.data ...everytime gets sorted, state.data gets mutated...which not suppose happen. real question is. why? or missunderstand redux?

if have @ .sort() says

the sort() method sorts elements of array in place , returns array

so mapstatetoprops mutating state. there's nothing in redux stops doing this, have take care of keeping state immutable yourself.

this should solved using (for example)

return [...state.data].sort() 

or other way clone array before sorting it.

you can replicate in browser console running these 2 lines , comparing output

var = [2,1]; console.log(a.sort()); console.log(a) var = [2,1]; console.log([...a].sort()); console.log(a) 

the first 1 change original array, second not.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -