【问题标题】:Local Storage Keeps Resetting On Page Reload本地存储在页面重新加载时不断重置
【发布时间】:2020-11-19 08:25:34
【问题描述】:

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

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

【问题讨论】:

  • 你的组件做的第一件事就是用这一行将 localStorage 设置为一个空值:localStorage.setItem('boards', JSON.stringify(boards));
  • 好的,那么有什么更好的方法。请原谅我是新手
  • 假设您只想在对列表进行一些更改时写入 localStorage,然后将该行代码移动到您的更改处理程序。
  • 当我这样做时,它根本不会更新本地存储,即使没有重新加载本地存储仍然是一个空数组
  • 对 - 你有两个变更处理程序 - 对吧?

标签: javascript arrays reactjs local-storage


【解决方案1】:

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

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

【讨论】:

  • 哦,我明白了,非常感谢。我在这上面呆了一整天。抱歉我回复晚了,再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多