简体   繁体   English

React Redux状态不替换

[英]React Redux state not replacing

I am trying to fetch a new batch of products through an action and then replace the state with the new batch, however it just adds it to the array... 我正在尝试通过操作来获取新一批产品,然后用新批次替换状态,但是它只是将其添加到阵列中...

Here's my reducer for controlling the state: 这是我控制状态的减速器:

const initialState = {
  fetching: false,
  fetched: false,
  Brands:[],
  Markings:[],
  Products: [],
  error: null
}

export default function reducer(state=initialState, action=null) {
  switch (action.type){

    case "FETCH_PRODUCTS_PENDING" : {
      return {...state}
      break;
    }
    case "FETCH_PRODUCTS_REJECTED" : {
      return {...state}
      break;
    }
    case "FETCH_PRODUCTS_FULFILLED" : {
      return{ ...state, 
        Products: state.Products.concat(action.payload.data.Products),
        Brands: action.payload.data.Facets[0].Facets,
        Markings: action.payload.data.Facets[1].Facets
      }
      break;
    }
  }
  return state
}

It goes wrong in the fulfilled case.. I am not sure how this "...state" works, do I need to do a object assign or something? 在完成的情况下它出错了。我不确定此“ ...状态”如何工作,我是否需要进行对象分配或其他操作?

Upon load I get 52 products, when trying to request a new batch it adds it up so my this.props.products is 104 items... I want it to replace 加载后,我得到52种产品,当尝试请求一个新批次时,它会加起来,因此我的this.props.products是104个项目...我要替换它

This line is the culprit 这是罪魁祸首

Products: state.Products.concat(action.payload.data.Products),

In this case all you want to do is replace the Products array with the one from the action. 在这种情况下,您要做的就是用操作中的那个替换Products数组。

So it should be simply 所以应该简单

Products: action.payload.data.Products

See here for a nice explanation on the spread operator : https://ponyfoo.com/articles/es6-spread-and-butter-in-depth 请参阅此处以了解有关spread operator说明: https : //ponyfoo.com/articles/es6-spread-and-butter-in-depth

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

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