简体   繁体   中英

React Redux: How to add a property to an empty object in the reducer

const INITIAL_STATE = {
  editedProduct: {},
};

reducer.js

   case ADD_SWATCH:
      const typeSwatch = action.payload;
      return merge(state, {
        editedProduct: {
          ...state.editedProduct,
          [typeSwatch]: [
            ...state.editedProduct[typeSwatch],
            {
              dimSwtNo: state.editedProduct[typeSwatch].length
                ? state.editedProduct[typeSwatch].length + 1
                : 1,
            },
          ],
        },
      });

I get an error: Possible Unhandled Promise Rejection (id: 0): TypeError: Invalid attempt to spread non-iterable instance

The problem is in this line

...state.editedProduct[typeSwatch],

Refers to a property that has not yet been initialized.

How could I solve this problem?

As the error suggests, you can't spread a null / undefined value. The simplest approach here is to use a default value in scenarios where the property has not been set yet eg

...(state.editedProduct[typeSwatch] || [])

Since you use this value in a couple of places it would make sense to create a variable further up.

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