previous state in reducers in redux with react

て烟熏妆下的殇ゞ 提交于 2019-12-23 01:02:01

问题


Here is what my reducer looks like:

export default function catalogReducer(state = initialState.catalogItems, action){
  switch (action.type) {
    case types.LOAD_CATALOG_SUCCESS:
      return {
         count:action.count,
        products :[...state['products'],
        action.catalogItems  ?
        [...action.catalogItems['products']]
          :
          []
      ]
    default:
      return state;
  }
}

What I want to do:

  1. This is a reducer for loading catalog items

  2. Items are coming from a paginated api.

  3. I need to add results from api to existing list of products

Problem:

I was hoping that state argument should would have the previous state associated but no, it is always getting value from initialState which what I initialize the state with on application startup.

Why is that? What is the way around for it?

Basically I need to have the complete set of items returned through pagination api and not just the products for a given page in products array. What I am ending up with is just the array of products from last api call as state.products always gets initialized as an empty array

Also, generally speaking I am very confused about dealing with pagination api in react and redux and am not able to find a straightforward example.

A direction would be appreciated.

This is what initialState.js file looks like:

import cookie from 'react-cookie';

export default {
 categories:[],
  sessionId: cookie.load('sessionId') || '',
  youMayLikeItems : [],
  catalogItems: {'products': []}
}

//This file is to centralize initialization of states in the store


回答1:


Basically, you need to remember that you shouldn't mutate state.

export default function catalogReducer(state = initialState, action) {
  switch (action.type) {
    case types.LOAD_CATALOG_SUCCESS:
      return {
        ...state,
        catalogItems: {
          count: action.count,                          
          products: [
            ...state.catalogItems['products'],
            action.catalogItems  ?
              action.catalogItems['products']
              :
              {}
          ]
        }
  default:
    return state;
  }
}

You could find more useful examples here

Also it's better to make simple states (docs) without deep objects and use Immutable.js



来源:https://stackoverflow.com/questions/41909566/previous-state-in-reducers-in-redux-with-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!