开发者问题收集

为什么我无法访问从 redux store 获取的产品?

2019-12-28
38

我的产品列表 Reducer 如下所示:

const initialState = {
    products: [],

    productListSidebars: [],
    banners: ['enjoy.png', 'account.png']
}

export const ProductListReducer = (state = initialState, action) => {
switch (action.type) {
    case SET_PRODUCTS:
        const newState = state;
        newState.products = action.payload;
        console.log('newState', newState)
        return newState;
    }
}

当我在组件的 render 方法中将从商店检索到的 props.productList 记录到控制台时,如下所示:

render() {
    console.log('props.prodList ', this.props.productList)
}

它显示以下内容:

{products: Array(0), productListSidebars: Array(3), banners: Array(2)}

如您所见,它表示数组 props.productList.products 包含 0 个数据。但是,当我在控制台中展开 props.productList 时,它显示 props.productList.products 实际上包含 4 个产品。

props.prodList  
{products: Array(0), productListSidebars: Array(3), banners: Array(2)}
products: Array(4)
0: {images: Array(1), categories: Array(0), _id: "5db6fc687c213e556144ae7b", name: "Signature Gold 
Collection Tailored Fit Herringbone Suit", price: 990, …}
1: {images: Array(1), categories: Array(0), _id: "5db6fd127c213e556144aecd", name: "Executive 
Collection Tailored Fit Suit", price: 790, …}
2: {images: Array(1), categories: Array(0), _id: "5db6fd997c213e556144aef5", name: "Executive 
Collection Traditional Fit Suit", price: 690, …}
3: {images: Array(5), categories: Array(0), _id: "5db6fa6c7c213e556144ad28", name: "Signature Gold 
Collection Tailored Fit Suit", price: 960, …}
length: 4
__proto__: Array(0)
productListSidebars: (3) [{…}, {…}, {…}]
banners: (2) ["enjoy.png", "bank-account.png"]
__proto__: Object

当我尝试访问如下所示的产品时,它给了我一个空数组,即使有 4 个产品如上所示:

const { products } = this.props.productList;
console.log('products', products)
2个回答

更新 必须 是不可变的,您不能直接改变 状态

immutable-update-patterns

switch (action.type) {
  case SET_PRODUCTS:
    return {
      ...state,
      products: action.payload
    }
}
Asaf Aviv
2019-12-28

我不熟悉 redux,但在 vanilla RxJS 中,如果您没有订阅执行操作时对产品列表的更改,您将不会收到更新,因为列表应该完全封装在商店中,您只会收到一份副本,而不是引用。

weagle08
2019-12-28