[英]How to i save a new entry in array to local storage?
我有一个组件,我在其中添加了一个新的播放列表,我制作了一个 function 来向播放列表数组添加一个播放列表,但是当我刷新页面时,新条目消失了。 我试图保存到 localStroge,但它似乎不起作用? 我该如何解决? 我还有一个 db.json 文件,我可以在其中获取播放列表数据,如果 localStorage 不起作用,我可以保存在那里吗?
import axios from "axios";
import {
Box,
Button,
CircularProgress,
Stack,
TextField,
Typography,
} from "@mui/material";
import MIcons from "../Utils/MIcons";
import PlayLists, { PlayListValues } from "./PlayLists";
const Home = () => {
const [playLists, setPlayLists] = useState<PlayListValues[]>([]);
const [newList, setNewList] = useState("");
useEffect(() => {
try {
axios.get(`http://localhost:3000/playList`).then((res) => {
const response = res.data;
setPlayLists(response);
});
} catch (err) {
console.debug(err, "error");
}
}, []);
const addPlayList = () => {
if (newList) {
let num = playLists?.length + 1;
let newEntry = { id: num, title: newList, songs: [] };
setPlayLists([...playLists, newEntry]);
}
};
useEffect(() => {
localStorage.setItem("playLists", JSON.stringify(playLists));
}, [playLists]);
console.log(playLists, "playlist");
return (
<Box>
<Stack direction="row" spacing={2} justifyContent="space-between" m={2}>
<Stack direction="row" spacing={2}>
<MIcons.LibraryMusic />
<Typography variant="subtitle1">Your playlists</Typography>
</Stack>
</Stack>
<Stack direction="row" spacing={2} m={2} justifyContent="center">
{playLists && <PlayLists playList={playLists} />}
{!playLists && <CircularProgress />}
</Stack>
<TextField
label="Add playList"
variant="outlined"
value={newList}
onChange={(e) => setNewList(e.target.value)}
/>
<Button onClick={addPlayList}>add</Button>
</Box>
);
};
export default Home;
只需从 localStorage 设置初始值
const [playLists, setPlayLists] = useState<PlayListValues[]>(localStorage.getItem('playLists') || []);
您编写了一个 useEffect 渲染播放列表 state 上的所有更改,因此当您刷新浏览器时,组件再次渲染,播放列表 state 的初始值是 [] 您的 useEffect 调用的空数组并在 localStorage 中设置空数组。 因此,您应该将 localStorage:setItem 包装在如下条件中:
useEffect(() => {
if(!!playLists.length){
localStorage.setItem("playLists", JSON.stringify(playLists));
}
}, [playLists]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.