简体   繁体   English

本地存储在页面重新加载时不断重置

[英]Local Storage Keeps Resetting On Page Reload

I'm trying to use local storage to store and array it works but when I reload it resets the array.我正在尝试使用本地存储来存储和排列它可以工作,但是当我重新加载它时它会重置数组。 I have looked through some similar questions and did everything I could understand from the answers provided, so I guessed the problem might be from my code so please help me review it.我已经浏览了一些类似的问题,并从所提供的答案中尽了我所能理解的一切,所以我猜这个问题可能来自我的代码,所以请帮我检查一下。 Thanks in advance提前致谢

import React, { useState } from 'react'
import Modal from './Modal'


function Boards() {
    const [boards, setboards] = useState([]);
    const [title, settitle] = useState('');

    localStorage.setItem('boards', JSON.stringify(boards));

    let storedboards = JSON.parse(localStorage.getItem('boards')) || [];

    const handleChange = (e) => {
        settitle(e.target.value)
    }
    const handleSubmit = () => {
        if (title.length === 0) {
            return;
        }
        setboards(prev => (
            [
                ...prev,
                title
            ]
        ))
    }
    return (
        <div>
            <ul id="boards">
                <BoardList boards={boards} />
            </ul>
            <Modal title={title} handleChange={handleChange} handleSubmit={handleSubmit} />
        </div>
    )
}
function BoardList({ boards }) {
    const history = useHistory()
    return (
        <>
            {
                boards.map((board, index) => (
                    <li key={index} onClick={() => { history.push('./workspace') }}>
                        <h3>{board}</h3>
                    </li>
                ))}

        </>
    )
}
export default Boards

It's reseting the array when you reload, because of this:重新加载时它会重置数组,因为:

function Boards() {
  // you're creating a state variable with an empty array
  const [boards, setboards] = useState([]);

  // you're overriding the item `boards` on the local storage
  localStorage.setItem('boards', JSON.stringify(boards));

Try a slight change like this:尝试这样的轻微改变:

function Boards() {
  // try to load `boards` from the local storage, if null set empty array to the var
  const storedboards = JSON.parse(localStorage.getItem("boards")) || [];

  // use the above var to create the state variable
  // if you have `boards` in the local storage, the value will be the recovered value
  // otherwise the initial value for this state will be an empty array
  const [boards, setboards] = useState(storedboards);

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

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