简体   繁体   中英

Working of push in react while using redux to update the state

The following code is the code for my reducer where i am calling these function in my container

const intialState = {
  counter: 0,
  results: []
};

const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        counter: state.counter + 1
      };

    case "STORE_RESULT": {
      return {
        ...state,
        results: state.results.push(state.counter)
      };
    }
  }
  return state;
};

export default reducer;

I am getting following error

TypeError: state.results.push is not a function
reducer

1) I am using redux reducer in my project

2) I am updating the state by passing the type from my dispatch in my container

3) I am trying to update the array by pushing(i know it returns the length ) but i want to know why it is not working

4) Following code i tryed in javascript everything worked fine

var a = {
b:[]
}
a.b.push(11)
//output
1

push returns the new length of the mutated array . Use concat instead which returns a new array

results : state.results.concat(item)

Let's assume the following code

results : state.results.push('foo')

Assuming that results has a length of 5 , the above code will assert to

results : 5

Next time you try to push results this is what will look like to your compiler

5.push('foo')

the return value of .push is

The new length property of the object upon which the method was called.

to add the value to stae.results use concat or spread syntax :

case "STORE_RESULT": {
  return {
    ...state,
    results: [...state.results, state.counter]
  };
}

you should add default case in reducer switch.

and use the [...state.results, state.counter] instead of state.results.push(state.counter) .

like this

const intialState = {
  counter: 0,
  results: []
};

const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        counter: state.counter + 1
      };

    case "STORE_RESULT": {
      return {
        ...state,
        results: [...state.results, state.counter] // here
      };
    default:
      return state; // here
    }
  }
};

export default reducer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM