本地存储在我的应用中工作不正常。

huangapple go评论82阅读模式
英文:

localStorage is working wrong in my application

问题

我在我的应用程序中遇到了与localStorage相关的问题。当我将项目添加到“收藏夹”列表时,它们会被顺利存储在localStorage中,甚至可以通过再次点击它们来删除。

但是,当我刷新页面时,我的应用程序无法读取这些项目在收藏夹列表中,并且不会标记它们。而且,当我向收藏夹列表中添加新项目时,它会导致删除localStorage中的所有内容并重新开始。

以下是localStorage视图的GIF图像

本地存储在我的应用中工作不正常。

以下是代码:

import React, { useState, useEffect } from 'react';
import SearchBar from '../../SearchBar/SearchBar.js';
import FiltersBox from '../FiltersBox/FiltersBox.js';
import { getItems } from '../../../Database/Database.js';
import './ItemsContainer.css';

function ItemsContainer() {
	const [items, setItems] = useState([]);
	const [search, setSearch] = useState('');

	const [favoriteItems, setFavoriteItems] = useState([]);
	let localItems = localStorage.getItem('Favorite Items');

	const [sortPrice, setSortPrice] = useState('');
	const [filterCategory, setFilterCategory] = useState('');

	const addItemToFavorites = item => {
		let existentItem = favoriteItems.find(favItem => favItem.id === item.id);

		if (existentItem) {
			let filterTheExistentItem = favoriteItems.filter(
				favItem => item.title !== favItem.title
			);

			setFavoriteItems(filterTheExistentItem);

			let stringItems = JSON.stringify(filterTheExistentItem);
			localStorage.setItem('Favorite Items', stringItems);
		} else {
			setFavoriteItems([...favoriteItems, item]);

			let stringItems = JSON.stringify([...favoriteItems, item]);
			localStorage.setItem('Favorite Items', stringItems);
		}
	};

	const filteredItemsList = () => {
		let newItemList = [];

		newItemList = items.filter(item => {
			if (filterCategory !== '' && filterCategory !== 'none') {
				return item.category === filterCategory;
			} else {
				return item;
			}
		});

		if (sortPrice === 'ascending') {
			return newItemList.sort((a, b) => (a.price > b.price ? 1 : -1));
		} else if (sortPrice === 'descending') {
			return newItemList.sort((a, b) => (b.price > a.price ? 1 : -1));
		} else {
			return newItemList;
		}
	};

	function onSortSelected(sortValue) {
		setSortPrice(sortValue);
	}

	function onCategorySelected(categoryValue) {
		setFilterCategory(categoryValue);
	}

	useEffect(() => {
		getItems().then(res => setItems(res));
	}, []);

	useEffect(() => {
		let xd = JSON.parse(localItems);
		console.log(xd);
	}, [localItems]);

	return (
		<div>
			<SearchBar setSearch={setSearch} />
			<FiltersBox
				items={items}
				setItems={setItems}
				onSortSelected={onSortSelected}
				onCategorySelected={onCategorySelected}
			/>
			<div>
				{filteredItemsList()
					.filter(item =>
						search.toLowerCase() === ''
							? item
							: item.title.toLowerCase().includes(search)
					)
					.map(item => (
						<div key={item.id}>
							<div>{item.title}</div>
							<button
								className={favoriteItems.includes(item) ? 'si' : 'no'}
								onClick={() => addItemToFavorites(item)}>
								Add to favorites
							</button>
						</div>
					))}
			</div>
		</div>
	);
}

export default ItemsContainer;

这里我留下了一个连续的localStorage控制台日志的GIF图像:

本地存储在我的应用中工作不正常。

我尝试了所有方法,但不知道发生了什么。

英文:

I have a problem with the localStorage in my application. When I add items to a list of "favorites" they are stored without any problem in the localStorage, they can even be deleted by clicking them again.

But when I refresh the page, my application doesn't read that these items are in the favorites list and therefore doesn't mark them. Also, when I add a new item to the favorites list it causes it to delete everything from localStorage and start over.

Here's a gif of the localStorage view

本地存储在我的应用中工作不正常。

Here's the code:

import React, { useState, useEffect } from &#39;react&#39;;
import SearchBar from &#39;../../SearchBar/SearchBar.js&#39;;
import FiltersBox from &#39;../FiltersBox/FiltersBox.js&#39;;
import { getItems } from &#39;../../../Database/Database.js&#39;;
import &#39;./ItemsContainer.css&#39;;
function ItemsContainer() {
const [items, setItems] = useState([]);
const [search, setSearch] = useState(&#39;&#39;);
const [favoriteItems, setFavoriteItems] = useState([]);
let localItems = localStorage.getItem(&#39;Favorite Items&#39;);
const [sortPrice, setSortPrice] = useState(&#39;&#39;);
const [filterCategory, setFilterCategory] = useState(&#39;&#39;);
const addItemToFavorites = item =&gt; {
let existentItem = favoriteItems.find(favItem =&gt; favItem.id === item.id);
if (existentItem) {
let filterTheExistentItem = favoriteItems.filter(
favItem =&gt; item.title !== favItem.title
);
setFavoriteItems(filterTheExistentItem);
let stringItems = JSON.stringify(filterTheExistentItem);
localStorage.setItem(&#39;Favorite Items&#39;, stringItems);
} else {
setFavoriteItems([...favoriteItems, item]);
let stringItems = JSON.stringify([...favoriteItems, item]);
localStorage.setItem(&#39;Favorite Items&#39;, stringItems);
}
};
const filteredItemsList = () =&gt; {
let newItemList = [];
newItemList = items.filter(item =&gt; {
if (filterCategory !== &#39;&#39; &amp;&amp; filterCategory !== &#39;none&#39;) {
return item.category === filterCategory;
} else {
return item;
}
});
if (sortPrice === &#39;ascending&#39;) {
return newItemList.sort((a, b) =&gt; (a.price &gt; b.price ? 1 : -1));
} else if (sortPrice === &#39;descending&#39;) {
return newItemList.sort((a, b) =&gt; (b.price &gt; a.price ? 1 : -1));
} else {
return newItemList;
}
};
function onSortSelected(sortValue) {
setSortPrice(sortValue);
}
function onCategorySelected(categoryValue) {
setFilterCategory(categoryValue);
}
useEffect(() =&gt; {
getItems().then(res =&gt; setItems(res));
}, []);
useEffect(() =&gt; {
let xd = JSON.parse(localItems);
console.log(xd);
}, [localItems]);
return (
&lt;div&gt;
&lt;SearchBar setSearch={setSearch} /&gt;
&lt;FiltersBox
items={items}
setItems={setItems}
onSortSelected={onSortSelected}
onCategorySelected={onCategorySelected}
/&gt;
&lt;div&gt;
{filteredItemsList()
.filter(item =&gt;
search.toLowerCase() === &#39;&#39;
? item
: item.title.toLowerCase().includes(search)
)
.map(item =&gt; (
&lt;div key={item.id}&gt;
&lt;div&gt;{item.title}&lt;/div&gt;
&lt;button
className={favoriteItems.includes(item) ? &#39;si&#39; : &#39;no&#39;}
onClick={() =&gt; addItemToFavorites(item)}&gt;
Add to favorites
&lt;/button&gt;
&lt;/div&gt;
))}
&lt;/div&gt;
&lt;/div&gt;
);
}
export default ItemsContainer;

And here I leave a GIF with a continuous console.log of the localStorage:

本地存储在我的应用中工作不正常。

I tried everyrhing, and I don't know what is happening.

答案1

得分: 2

你正在从localItems中检索你的物品,但是... 你没有对这个变量进行任何操作。你应该使用本地存储来初始化你的状态favoritesItems

const getItemsFromLocalStorage = () => {
  const items = localStorage.getItem('Favorite Items');
  return items ? JSON.parse(items) : [];
}

const [favoriteItems, setFavoriteItems] = useState(getItemsFromLocalStorage())
英文:

You're retrieving your items in localItems and... you do nothing with this variable. You should initialize your state favoritesItems with your local storage

const getItemsFromLocalStorage = () =&gt; {
  const items = localStorage.getItem(&#39;Favorite Items&#39;);
  return items ? JSON.parse(items) : [];
}


const [favoriteItems, setFavoriteItems] = useState(getItemsFromLocalStorage())

答案2

得分: 0

这是罪魁祸首所在:

const [favoriteItems, setFavoriteItems] = useState([]);
let localItems = localStorage.getItem('Favorite Items');

你将 localStorage 加载到了 localItems 中,但你期望它在 favoriteItems 中,而你从未对它进行赋值。你需要将 localStorage 中的项指定为初始状态,像这样:

let localItems = localStorage.getItem('Favorite Items');
const [favoriteItems, setFavoriteItems] = useState(localItems ? localItems : []);
英文:

This is where the culprit is:

    const [favoriteItems, setFavoriteItems] = useState([]);
let localItems = localStorage.getItem(&#39;Favorite Items&#39;);

You load localStorage into localItems, but you expect it to be in favoriteItems, where you have never assigned it. You would need to specify the item of localStorage as the initial state, like:

    let localItems = localStorage.getItem(&#39;Favorite Items&#39;);
const [favoriteItems, setFavoriteItems] = useState(localItems ? localItems : []);

huangapple
  • 本文由 发表于 2023年1月9日 02:29:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定