我已经为用户创建了将他们最喜欢的食谱添加到列表中的功能,然后他们可以查看他们保存的食谱的列表,但是我正在try 将食谱数组保存到本地存储中,这样数据在刷新时就不会丢失.
我已经保存了数据,并try 将状态更新为本地存储中的状态,但数据不会持久存在
const [myRecipeState, dispatchMyRecipes] = useReducer(myRecipesReducer, {items: []});
const addItemHandler = (item) => {
dispatchMyRecipes({val:'ADD', item: item});
}
const removeItemHandler = (id) => {
dispatchMyRecipes({val:'REMOVE', id: id});
}
const myRecipesReducer = (state, action) => {
if (action.val === 'ADD') {
let updatedItems;
let updatedItem;
const existingItemIndex = state.items.findIndex(item => item.id === action.item.id)
const existingItem = state.items[existingItemIndex];
const localRecipes = JSON.parse(localStorage.getItem('myRecipes'));
if (existingItem) {
updatedItems = [...state.items];
updatedItem = existingItem;
updatedItems[existingItemIndex] = updatedItem;
console.log('item already exists');
localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
}else {
updatedItems = state.items.concat(action.item);
console.log('item added for the first time');
localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
}
return {items: localRecipes || updatedItems}
}
if (action.val === 'REMOVE') {
let updatedItems;
const localRecipes = JSON.parse(localStorage.getItem('myRecipes'));
updatedItems = [...state.items].filter(item => item.id !== action.id);
localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
return {items: localRecipes || updatedItemsupdatedItems}
}
return {items: state.items}
}