简体   繁体   English

使用redux根据当前值更新对象数组中的单个对象属性

[英]Update a single object property in an array of objects based on the current value with redux

Within my state, I have an array of objects that have a few descriptive properties, a quantity, and a unique id. 在我的状态内,我有一个对象数组,这些对象具有一些描述性属性,数量和唯一ID。 The data within this object comes back from an API response, and within my action creator, I check the state to see if it exists already and if so dispatch an increment action for my reducer. 该对象中的数据从API响应返回,并且在我的操作创建者中,我检查状态以查看其是否已经存在,如果存在,则为我的reducer调度一个增量操作。 This is what my action creator looks like: 这是我的动作创建者的样子:

export const getProductDetails = upc => (dispatch, getState) => {
const state = getState();
const products = state.table.products;
if (_find(products, upc) !== undefined) {
  dispatch({ type: INCREMENT_QUANTITY, payload: upc });
} else {
axios
  .post(<--POST TO ENDPOINT-->) }
  })
  .then(res => {
    dispatch({ type: POST_UPC, payload: res.data });
  })
  .catch(err => {
    errorHandler(dispatch, err.response, AUTH_ERROR);
  });
 }
};

My reducer for this case looks is structured as so: 我针对这种情况的减速器的结构如下:

case INCREMENT_QUANTITY:
  return {
    ...state,
    products: state.products.map(product => {
      action.payload === product.upc
        ? { ...product, quantity: product.quantity + 1 }
        : product;
    })
  };

I based this reducer logic from this this excellent response , but for some reason when the action is dispatched, the duplicate product is overwritten as null instead of incrementing the quantity as expected. 我基于这种出色的响应来构建减速器逻辑,但是由于某种原因,在分派操作时,重复产品被覆盖为null而不是按预期增加数量。 I'm still trying to learn redux right now, so forgive my ignorance. 我现在仍在尝试学习redux,请原谅我的无知。 Ideally, I'd like to avoid bringing in a library or package just to increment a value. 理想情况下,我想避免引入库或包只是为了增加一个值。 What exactly am I missing within my reducer? 我的减速器中到底缺少什么?

You're not returning anything in your map callback, you're creating a block thus you don't get the intended result. 您没有在map回调中返回任何内容,而是在创建一个块,因此无法获得预期的结果。 Instead, omit the brackets { … } : 而是省略括号{ … }

products: state.products.map(product => 
  action.payload === product.upc
    ? { ...product, quantity: product.quantity + 1 }
    : product;
);

This will use arrow function syntax to implicitly return the result of the ternary operator. 这将使用箭头函数语法隐式返回三元运算符的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM