javascript - 本地存储在页面重新加载时不断重置
问题描述
我正在尝试使用本地存储来存储和排列它,但是当我重新加载它时,它会重置阵列。我查看了一些类似的问题,并从提供的答案中做了我能理解的一切,所以我猜问题可能出在我的代码上,所以请帮我检查一下。提前致谢
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
解决方案
重新加载时它会重置数组,因为:
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);
推荐阅读
- python - Python 3.8 - UDP 接收在第二个以太网端口(usb 以太网)上不起作用
- javascript - Redux-Form 收到警告:使用 UNSAFE_componentWillReceiveProps
- r - 使用 dplyr mutate 函数替换多个值
- asp.net - 获取实体框架表中的所有行
- netcdf - 如何使用雪貂或 cdo 遮盖脸盆
- c++ - 如何使用传递给编译器的相同参数在 cmake 中运行命令?
- ansible - 检查条件何时不是ansible中的值
- r - R 函数 dbGetQuery 从函数 dbConnect 返回名称为 1x1 的表
- android - 带有Android应用程序的离子项目中的多个环境
- qt - 我如何重定向到另一个页面,或者我可以链接我的 qml 文件。qt创建者