无法从 redux 存储中删除对象
Posted
技术标签:
【中文标题】无法从 redux 存储中删除对象【英文标题】:Can't delete object from redux store 【发布时间】: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 未定义
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于无法从 redux 存储中删除对象的主要内容,如果未能解决你的问题,请参考以下文章