1

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, useEffect } from 'react'
import Modal from './Modal'


function Boards() {
    const [boards, setboards] = useState(JSON.parse(localStorage.getItem('boards')) || []);
    const [title, settitle] = useState('');
    localStorage.setItem('boards', JSON.stringify(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

4

1 回答 1

2

set your initial boards state to the boards in localStorage

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


function Boards() {
    const [boards, setboards] = useState( JSON.parse(localStorage.getItem('boards') || []);
    const [title, settitle] = useState('');
    localStorage.setItem('boards', JSON.stringify(boards));


    const handleChange = (e) => {
        settitle(e.target.value)
    }
    const handleSubmit = () => {
        if (title.length === 0) {
            return;
        }
        setboards(prev => (
            [
                ...prev,
                title
            ]
        ))
        localStorage.setItem('boards', JSON.stringify(boards));


    }
    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
于 2020-11-18T21:01:03.937 回答