简体   繁体   English

如何将数组中的新条目保存到本地存储?

[英]How to i save a new entry in array to local storage?

I have an comoponent where i add a new playlist, I've made a function to add a playlist to the playlist array, but when i refresh the page, de new entry is gone.我有一个组件,我在其中添加了一个新的播放列表,我制作了一个 function 来向播放列表数组添加一个播放列表,但是当我刷新页面时,新条目消失了。 i have tried to save to localStroge, but it doesn't seem te work?我试图保存到 localStroge,但它似乎不起作用? how do i fix this?我该如何解决? I also have a db.json file where i fetch the playlist data, can i possibly save there if localStorage wont work?我还有一个 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;

Just set the initial value from localStorage只需从 localStorage 设置初始值

const [playLists, setPlayLists] = useState<PlayListValues[]>(localStorage.getItem('playLists') || []);

You wrote an useEffect that render every change on your playList state, So when you refresh your browser the component render again and the playlist state got its initial value that is [] empty array the your useEffect called and set empty array in localStorage.您编写了一个 useEffect 渲染播放列表 state 上的所有更改,因此当您刷新浏览器时,组件再次渲染,播放列表 state 的初始值是 [] 您的 useEffect 调用的空数组并在 localStorage 中设置空数组。 So you should wrap your localStorage:setItem in a condition like below:因此,您应该将 localStorage:setItem 包装在如下条件中:

useEffect(() => {
    if(!!playLists.length){
localStorage.setItem("playLists", JSON.stringify(playLists));
}
  }, [playLists]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM