React Context API中主数组无法存入LocalStorage问题求助
React Context 同步 LocalStorage 失败的修复方案
问题根源
useEffect 依赖与存储对象错误
你当前的 useEffect 监听的是初始化时的initialState,并且存储的也是这个固定初始值,而非 useReducer 更新后的实时state。initialState仅在组件挂载时生效,后续状态变更不会触发该 useEffect,导致 LocalStorage 无法同步更新。冗余类型定义
代码中的firstSate接口未被使用,可删除以简化代码。
修复后的完整代码
import { createContext, useReducer, ReactNode, FC, useEffect } from "react"; import { AppReducer } from "./AppReducer"; import { Log } from "../components/LoggingPage"; export interface maintask { taskName: string; id: number; logs: Log[] } export interface InitialState { mainlogs: maintask[]; } export interface addlog { id: number; log: Log; } export interface updatelog { mainId: number; updatedLog: Log; } export interface deleteLog { mainLogId: number; logId: number } interface loggings { id: number; log: Log } export interface GlobalContextTypes { state: InitialState; addMainLogs: (mainTask: maintask) => void; deleteMainLogs: (id: number) => void; addLogs: (addLog: loggings) => void; updateLogs: (updatelog: updatelog) => void; deleteLogs: (deleteLog: deleteLog) => void; } const defaultState: InitialState = { mainlogs: [] } const storedState = localStorage.getItem('state'); const initialState: InitialState = storedState ? JSON.parse(storedState) : defaultState; export const GlobalContext = createContext<GlobalContextTypes | null>(null); const GlobalProvider: FC<{ children: ReactNode }> = ({ children }): JSX.Element => { const [state, dispatch] = useReducer(AppReducer, initialState); // 监听实时 state,同步到 LocalStorage useEffect(() => { localStorage.setItem('state', JSON.stringify(state)) }, [state]) const addMainLogs = (newlog: maintask) => { dispatch({ type: 'ADD_MAIN_LOG', payload: newlog }); }; const deleteMainLogs = (id: number) => { dispatch({ type: 'DELETE_MAIN_LOG', payload: id }) } const addLogs = (addLog: addlog) => { dispatch({ type: 'ADD_LOGS', payload: addLog, }) } const updateLogs = (updatedLog: updatelog) => { dispatch({ type: 'UPDATE_LOGS', payload: updatedLog }) } const deleteLogs = (deleteLog: deleteLog) => { dispatch({ type: 'DELETE_LOGS', payload: deleteLog }) } const contextValue: GlobalContextTypes = { state, addMainLogs, deleteMainLogs, addLogs, updateLogs, deleteLogs, }; return ( <GlobalContext.Provider value={contextValue}> {children} </GlobalContext.Provider> ); } export default GlobalProvider;
关键修改点
- 将 useEffect 的依赖改为实时的
state,并存储state而非initialState,确保每次状态变更都同步到 LocalStorage。 - 将初始状态变量名从
state改为defaultState,避免与组件内的state变量重名,提升代码可读性。 - 删除了未使用的
firstSate接口。
内容的提问来源于stack exchange,提问作者Abay sankar s
相关产品推荐
相关产品推荐

