【问题标题】:Push is not a function in reduxpush 不是 redux 中的功能
【发布时间】:2021-06-06 18:00:23
【问题描述】:

我使用 redux 编写了一个简单的添加到购物车功能。当我尝试将产品添加到数组时,它会引发错误:

state.products.push 不是函数。

初始状态

export const INITIAL_STATE = {
  products: []
};

我使用 redux-sauce 来调度操作。

减速器

export const AddToCart = (state, { item }) => ({
  ...state,
  products: state.products.push(item),
});

【问题讨论】:

  • 在 reducer 中初始化 state=INITIAL_STATE
  • 初始状态与reducer状态相同
  • 将 push 更改为 concat。 Push 不返回数组。
  • 您能否在 AddToCart 中控制台日志状态并检查产品是否存在状态

标签: redux react-redux


【解决方案1】:

这里的主要问题是您将state.products 的值设置为push() 返回的值。 push() 方法不返回数组。它会改变数组,这在 Redux 中是不应该做的,returns the new length。调用此 reducer 后,您会将 state.products 属性从数组更改为 number

您可以改用concat()。此方法返回一个新数组,其中附加了项目。它不会修改原始数组,因此它是 Redux 安全的。

我对 redux-sauce 不太熟悉,但是 seems like 你需要在每个 case reducer 中包含 state = INITIAL_STATE

export const AddToCart = (state = INITIAL_STATE, { item }) => ({
  ...state,
  products: state.products.concat(item),
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2017-10-06
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多