首页 > 解决方案 > 本地存储在页面重新加载时不断重置

问题描述

我正在尝试使用本地存储来存储和排列它,但是当我重新加载它时,它会重置阵列。我查看了一些类似的问题,并从提供的答案中做了我能理解的一切,所以我猜问题可能出在我的代码上,所以请帮我检查一下。提前致谢

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

标签: javascriptarraysreactjslocal-storage

解决方案


重新加载时它会重置数组,因为:

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));

尝试这样的轻微改变:

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);

推荐阅读