将 React 上下文与本地存储一起使用

Use React Context With Local Storage

我正在尝试使用本地存储来存储我的阵列,但我不确定该怎么做。另外,我将如何做到每次状态更新时,本地存储都会同时更新?

当前代码:

import React, { useState, createContext } from 'react';
import { v4 as uuidv4 } from 'uuid';

export const NoteContext = createContext();

export const NoteProvider = props => {

    const [notes, setNotes] = useState([
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfffffffffffffffffffffffffffffffffffffff',title:'e', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
        
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false}
    
    ])
    return (
        <NoteContext.Provider value={[notes, setNotes]}>
            {props.children}
        </NoteContext.Provider>
    )

}

您可以从 localStorage 初始化您的状态,并使用 useEffect.

传播对它的更改
function getInitialState() {
  const notes = localStorage.getItem('notes')
  return notes ? JSON.parse(notes) : []
}

export const NoteProvider = props => {
  const [notes, setNotes] = useState(getInitialState)

  useEffect(() => {
    localStorage.setItem('notes', JSON.stringify(notes))
  }, [notes])
}

看看 MDN 上的 localStorage:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

本地存储就像一张地图,有键值对。为了将数组设置为本地存储,您首先必须将其转换为 json.

localStorage.setItem("notes", JSON.stringify(notes);

要检索项目,

const storedNotes = JSON.parse(localStorage.getItem("notes"));

最后,您可以创建一个函数来更新您的状态和存储

const updateStorageAndState = (newState) => {
  localStorage.setItem("notes", JSON.stringify(newState));
  setNotes(newState);
}