简体   繁体   中英

React Reducer Correct Way To Return An Array With State

I am using axios in the action creator and redux-promise middleware to return an array of objects to a map function in the render method of my component. When using the first return statement with ES6 spread, I get an array within an array. How would I properly iterate through this array? Would I use map in the reducer? The second return statement works. I am unclear as to why I wouldn't want just return the array by itself. Thanks!!

const INITIAL_STATE = [];

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case GET_TICKET:
            return [action.payload.data, ...state];
            return action.payload.data;
        default:
            return state;
    }
}

you can follow this format

const INITIAL_STATE = { data : [] };

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case GET_TICKET:
            return {...state, data: action.payload.data};
        default:
            return state;
    }
}

There's two main ways to combine two arrays into one:

const newArray = [...firstArray, ...secondArray];
// or
const newArray = firstArray.concat(secondArray);

Either of those will work in your case, like:

return state.concat(action.payload.data);

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