问题
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:
This is a reducer for loading catalog items
Items are coming from a paginated api.
- 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