Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在使用redux更新状态时使用push-in-react_Javascript_Reactjs_Redux_React Redux - Fatal编程技术网

Javascript 在使用redux更新状态时使用push-in-react

Javascript 在使用redux更新状态时使用push-in-react,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,下面的代码是我在容器中调用这些函数的reducer代码 const intialState = { counter: 0, results: [] }; const reducer = (state = intialState, action) => { switch (action.type) { case "INCREMENT": return { ...state, counter: state.counter + 1

下面的代码是我在容器中调用这些函数的reducer代码

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;
我得到以下错误

TypeError: state.results.push is not a function
reducer
1我在我的项目中使用redux reducer

2通过在容器中传递分派的类型,我正在更新状态

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;
3我试图通过按下按钮来更新数组我知道它返回长度,但我想知道它为什么不工作

4下面的代码我在javascript中尝试过,一切都很好

var a = {
b:[]
}
a.b.push(11)
//output
1
当然,推就是

调用方法的对象的新长度属性

要将值添加到stae.results,请使用或:


您应该在减速器开关中添加默认大小写

并使用[…state.results,state.counter]而不是state.results.pushstate.counter

像这样

push返回变异数组的新长度。使用concat返回一个新数组

results : state.results.concat(item)
让我们假设以下代码

results : state.results.push('foo')
假设结果的长度为5,上述代码将断言为

results : 5
下一次尝试推送结果时,编译器会这样认为

5.push('foo')

推送变异,你不应该变异。此外,push不会返回任何内容,所以我想您是想使用concatI的,只是想说上面的内容:try results:state.results.concat[state.counter],并告诉我们它是否工作。concat工作正常,但我想知道为什么push Failed push不会返回新阵列。你在结果中存储了一个int确定我想我的结果应该是一个数组,但我给出了一个数字,所以它抛出了错误concat worked,但思考了为什么推送失败如果错误请更正我什么是错误意味着state.results.push不是一个函数更新了答案不知道推送返回长度。凉的好的,我想我的结果应该是一个数组,但我给出了一个数字,所以它抛出了错误concat,但我想为什么push失败了,如果是错误的,请更正我错误意味着什么
5.push('foo')