【问题标题】:Can't delete object from redux store无法从 redux 存储中删除对象
【发布时间】:2021-11-23 19:05:31
【问题描述】:
import { createSlice } from "@reduxjs/toolkit";

const transactionSlice = createSlice({
    name: 'transactions',
    initialState: [
        {id: 1, text: 'shady', amount: 55},
        {id: 2, text: 'shady', amount: 55},
        {id: 3, text: 'shady', amount: 55}
    ],
    reducers: {
        addTransaction: (state, action) => {
            const newTransaction = {
                id: Math.floor(Math.random() * 100000),
                text: action.payload.text,
                amount: +action.payload.amount
            }
            state.push(newTransaction);
        },
        deleteTransaction: (state, action) => ({
            ...state,
            transactions: state.transactions.filter(transaction => transaction.id !== action.payload.id)
        })
    }
})

export const { addTransaction, deleteTransaction } = transactionSlice.actions;
export default transactionSlice.reducer;

我想从商店中删除一笔交易及其退货
TypeError:无法访问属性“过滤器”,state.transactions 未定义

【问题讨论】:

    标签: reactjs redux react-redux redux-toolkit


    【解决方案1】:

    您得到这个是因为您所在的州没有任何名为交易的密钥。

    您可以通过将createSlice 方法中的initialState值更新为

    initialState: {
        transactions:[
            {id: 1, text: 'shady', amount: 55},
            {id: 2, text: 'shady', amount: 55},
            {id: 3, text: 'shady', amount: 55}
        ]
    }
    

    【讨论】:

      【解决方案2】:

      切片的状态是一个数组 - 例如,您推送到状态以添加交易。过滤状态以删除一个:

          deleteTransaction: (state, action) =>
              state.filter(transaction => transaction.id !== action.payload.id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 2021-12-28
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多