localStorage 在 React 中未正确保存数组

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

localStorage not properly saving array in React

问题

以下是翻译好的部分:

"Working on a forum and I need my topics to start not erasing upon refresh so that I can start checking whether or not the messages display properly."

  • "在论坛上工作,我希望在刷新页面时不要擦除我的主题,以便我可以开始检查消息是否正确显示。"

"I have it so each time I make a topic, the topic is stored as an object inside an array. Each object stores different types of information like the title of the topic, the message, the author and the date. The array is then sorted and mapped and displays all the information on the page."

  • "我已经设置,每当我创建一个主题时,该主题都被存储为数组中的一个对象。每个对象都存储不同类型的信息,如主题的标题、消息、作者和日期。然后,数组被排序和映射,并在页面上显示所有信息。"

"The addTopic function is used as an onClick for a form that pops up."

  • "addTopic 函数用作弹出窗口表单的点击事件。"

"I have my localStorage set up using a useEffect like it was suggested however every time I make a topic and refresh the page, the array still erases itself and I'm back to the original state. Please advice."

  • "我已经使用 useEffect 来设置我的本地存储,就像建议的那样,但每次我创建一个主题并刷新页面时,数组仍然会擦除,并且恢复到原始状态。请给予建议。"

"const [topic, setTopic] = useState([]);"

  • "const [topic, setTopic] = useState([]);"

"const [title, setTitle] = useState();"

  • "const [title, setTitle] = useState();"

"const [message, setMessage] = useState();"

  • "const [message, setMessage] = useState();"

"const addTopic = (e) => {"

  • "const addTopic = (e) => {"

"useEffect(() => {"

  • "useEffect(() => {"

"useEffect(() => {"

  • "useEffect(() => {"

"localStorage.setItem("topic", JSON.stringify(topic));"

  • "localStorage.setItem("topic", JSON.stringify(topic));"

"const topics = JSON.parse(localStorage.getItem("topic"));"

  • "const topics = JSON.parse(localStorage.getItem("topic"));"

"if (topics) {"

  • "if (topics) {"
英文:

Working on a forum and I need my topics to start not erasing upon refresh so that I can start checking whether or not the messages display properly.

I have it so each time I make a topic, the topic is stored as an object inside an array. Each object stores different types of information like the title of the topic, the message, the author and the date. The array is then sorted and mapped and displays all the information on the page.

The addTopic function is used as an onClick for a form that pops up.

I have my localStorage set up using a useEffect like it was suggested however every time I make a topic and refresh the page, the array still erases itself and I'm back to the original state. Please advice.

const [topic, setTopic] = useState([]);
    
const [title, setTitle] = useState();
const [message, setMessage] = useState();
    
const addTopic = (e) => {
   e.preventDefault();
    
   const updatedTopic = [
     ...topic,
     {
       title: title,
       message,
       author: "Dagger",
       date: new Date(),
       },
    ];
    
   setTopic(updatedTopic);

};
    
useEffect(() => {
   localStorage.setItem("topic", JSON.stringify(topic));
 }, [topic]);
    
useEffect(() => {
   const topics = JSON.parse(localStorage.getItem("topic"));
   if (topics) {
     setTopic(topic);
   }
}, []);

答案1

得分: 3

效果按顺序运行,所以当您刷新页面时,您在此处的代码将在执行getItem之前执行setItem

替代您第二个useEffect的方法是直接从localStorage初始化您的useState钩子:

  const [topic, setTopic] = useState(
    () => {
      const topicJson = localStorage.getItem("topic");
      return topicJson ? JSON.parse(topicJson) : [];
    });
英文:

Effects run in order, so when you refresh the page the code you have here is going to setItem before you getItem.

An alternative to your second useEffect there is to initialise your useState hook directly from the localStorage:

  const [topic, setTopic] = useState(
    () => {
      const topicJson = localStorage.getItem("topic");
      return topicJson ? JSON.parse(topicJson) : [];
    });

答案2

得分: 1

是的,原因是JSON.parse(localStorage.getItem("topic"))会返回字符串"undefined"而不是未定义的对象。
改成以下方式试试:

useEffect(() => {
   let topics = localStorage.getItem("topic");
   if (topics) {
     topics = JSON.parse(topics)
     setTopic(topics);
   }
}, []);
英文:

Yes the reason is JSON.parse(localStorage.getItem("topic")) gives you the string "undefined" instead of the object undefined.
Instead try doing

useEffect(() => {
   let topics = localStorage.getItem("topic");
   if (topics) {
     topics = JSON.parse(topics)
     setTopic(topics);
   }
}, []);

</details>



huangapple
  • 本文由 发表于 2023年2月19日 19:00:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499640.html
匿名

发表评论

匿名网友

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

确定