使用react、typescript、redux工具包从本地存储中删除单个项目



我正在使用rest countries api来获取所有国家/地区,我想将任何国家/地区添加到最喜欢的页面中,并将其保存在localstorage中,但在我创建的切片的localstorage数组中添加和删除一个项目时出错

这是我的代码

import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";
type Country = {
flags: {
svg: string;
};
name: {
common: string;
};
region: string;
capital: string[];
population: number;
};
interface initials {
post: Country[];
postNumber: number;
}
const temp = localStorage.getItem("postItem");
const tempNumber = localStorage.getItem("postNumber");
const initialState: initials = {
post: temp ? JSON.parse(temp) : [],
postNumber: tempNumber ? JSON.parse(tempNumber) : 0,
};
export const postSlice = createSlice({
name: "Post",
initialState,
reducers: {
addToFavourite: (state, action: PayloadAction<Country>) => {
state.post.push(action.payload), (state.postNumber += 1);
localStorage.setItem("postItem", JSON.stringify(state.post));
localStorage.setItem("postNumber", JSON.stringify(state.postNumber));
},
removeFavourite: (state, action: PayloadAction<string>) => {
const postId = action.payload;
const removeItem = (state.post = state.post.filter(
(post) => post.name.common !== postId,
));
state.post = removeItem;
localStorage.setItem("postItem", JSON.stringify(state.post));
},
},
});
export const { addToFavourite, removeFavourite } = postSlice.actions;
export default postSlice.reducer;
localStorage.removeItem('postItem');

在参数中给出密钥的名称,该名称在存储数据时使用

最新更新