簡體   English   中英

如何將數組中的新條目保存到本地存儲?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM