gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:47:15 24 4
gpt4 key购买 nike

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

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

关于javascript - 本地存储在页面重新加载时不断重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64903227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com