为了账号安全,请及时绑定邮箱和手机立即绑定

使用 redux 更新状态时推送反应的工作

使用 redux 更新状态时推送反应的工作

慕哥6287543 2021-10-29 13:50:37
以下代码是我在容器中调用这些函数的减速器的代码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 functionreducer1)我在我的项目中使用 redux reducer2)我通过在我的容器中传递来自我的调度的类型来更新状态3)我试图通过推送来更新数组(我知道它返回长度)但我想知道它为什么不起作用4)下面的代码我在javascript中尝试过一切正常var a = {b:[]}a.b.push(11)//output1
查看完整描述

3 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

push返回新length的 mutated array。使用concat,而不是返回一个新的数组

results : state.results.concat(item)

让我们假设以下代码

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

假设 results有一个lengthof 5,上面的代码将断言

results : 5

下次您尝试push results这样做时,您的编译器会是什么样子

5.push('foo')


查看完整回答
反对 回复 2021-10-29
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

返回值的.push就是


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


添加值以stae.results使用concat或spread 语法:


case "STORE_RESULT": {

  return {

    ...state,

    results: [...state.results, state.counter]

  };

}


查看完整回答
反对 回复 2021-10-29
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

您应该在减速器开关中添加默认情况。


并使用[...state.results, state.counter]代替state.results.push(state.counter)。


像这样


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;


查看完整回答
反对 回复 2021-10-29
  • 3 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信