简体   繁体   中英

How can I filter an array which is in react redux reducer state?

This is my reducer file in react

const initialState = {
    products: [
        {
            name: 'Icecream',
            inCart: false,
            num: 2
        },
        {
            name: 'Cake',
            inCart: true,
            num: 5
        }
    ]
};

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case REVERSE:
            let newProd = [ ...state.products ];

            newProd.filter((a) => {
                if (a.inCart === true) {
                    return a;
                }
            });

            console.log(newProd);

            return {
                ...state,
                products: newProd
            };
        default:
            return state;
    }
};

and this is the console log of newProd which shows the filter function doesn't work

0: {name: "Icecream", inCart: false, num: 2}
1: {name: "Cake", inCart: true, num: 5}
length: 2
__proto__: Array(0)

How can I filter the products array so I can only get the item that has inCart = true and replace it with the old products array?

Filter returns a new array & won't mutate the original one. You are filtering but not assigning the output of filter to a variable.

Do this

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case REVERSE:
            let newProd = state.products.filter((a) => { //<---- like this
                if (a.inCart === true) {
                    return a;
                }
            });

            console.log(newProd);

            return {
                ...state,
                products: newProd
            };
        default:
            return state;
    }
};

You can also do it in a single liner - like this:

...
case REVERSE:
    return {
        ...state,
        products: state.products.filter(a => a.inCart)
    };
...

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