因此,我有一个组件,单击该组件时必须将一个城市的ID存储在localStorage的数组中。我为此使用了一个自定义钩子,如下所述。我面临的问题是,只要单击该组件,它就会完全重写localStorage中的值,而不是推送新值。
import React, {useEffect, useState} from 'react';
import styled from 'styled-components';
const Container = styled.div`
background-color: white;
display: flex;
position: relative;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
cursor: pointer;
padding: 2rem;
margin-top: 2rem;
transition: all 0.2s ease;
border-radius: 5px;
box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.07);
&:hover{
box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.16);
transform: translateY(-3px);
}
`;
const SearchedCity = (props) => {
const [storedId, setId] = useLocalStorage('ids', []);
let handleId = () => {
setId(prev => [...prev, props.cityId]);
}
return (
<Container onClick={handleId}>
{props.children}
</Container>
)
}
const useLocalStorage = (key, initialValue) => {
const [storedId, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (err) {
console.error(err);
return initialValue;
}
});
const setValue = value => {
try {
const valueToStore =
value instanceof Function ? value(storedId) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (err) {
console.error(err);
}
};
return [storedId, setValue];
};
export default SearchedCity;
答案 0 :(得分:0)
在更新localStorage值之前,您可以执行以下操作:
const array = localStorage.get(yourKeyHere);
const parsedArray = array ? JSON.parse(array) : [];
const newArray = [...parsedArray, newItem];
localStorage.set(yourKeyHere, JSON.stringify(newArray));