【问题标题】:How can I filter an array which is in react redux reducer state?如何过滤处于 react redux reducer 状态的数组?
【发布时间】:2020-05-18 10:12:06
【问题描述】:

这是我在 react 中的 reducer 文件

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;
    }
};

这是 newProd 的控制台日志,显示过滤功能不起作用

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

如何过滤 products 数组,以便我只能获取 inCart = true 的项目并将其替换为旧 products 数组?

【问题讨论】:

    标签: javascript arrays reactjs redux


    【解决方案1】:

    过滤器返回一个新数组并且不会改变原始数组。您正在过滤,但没有将过滤器的输出分配给变量。

    这样做

    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;
        }
    };
    

    您也可以在单个班轮中执行此操作 - 如下所示:

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

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 2017-12-31
      • 2021-10-28
      • 2021-01-08
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多