You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React刷新页面时如何通过localStorage持久化保存id与index值

你读取失败的核心原因是:你是在跳转到子组件之后才执行localStorage.setItem写入数据的,包含Link的SettingMenu组件在跳转前访问localStorage时,对应数据还没有被写入,自然读不到值。

根据你需要用到数据的场景,对应实现方式如下:

场景1:父组件页面刷新后需要读取之前保存的id和index

你需要在ParentComponent的初始化挂载阶段读取localStorage,示例代码如下:

// ParentComponent 内部代码
import { useEffect, useState } from 'react'

const ParentComponent = () => {
  // 新增状态保存从localStorage读取到的面板数据
  const [savedPanelState, setSavedPanelState] = useState(null)

  useEffect(() => {
    // 组件首次挂载时读取缓存
    const cachedState = localStorage.getItem('myState')
    if (!cachedState) return
    try {
      const parsedState = JSON.parse(cachedState)
      setSavedPanelState(parsedState)
      // 拿到数据后可执行后续逻辑,比如恢复对应面板的展开状态
      // setShow(prev => ({...prev, [parsedState.panelId]: true}))
    } catch (err) {
      // 解析失败说明缓存损坏,直接清除无效缓存
      localStorage.removeItem('myState')
    }
  }, [])

  // 原有逻辑不变
  const eachComponent = (index, id, name) => (
    // 原有代码
  )
  // 其余原有代码
}

场景2:跳转后的子组件刷新时需要读取id和index

如果是子组件刷新后location.state丢失,你需要在子组件初始化时优先读缓存,示例代码如下:

// 跳转后的子组件内部代码
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'

const CsvFilePage = () => {
  const navigate = useNavigate()
  const [panelId, setPanelId] = useState(null)
  const [panelIndex, setPanelIndex] = useState(null)

  useEffect(() => {
    // 优先从路由状态取数
    if (location.state?.panelId && location.state?.panelIndex) {
      const { panelId, panelIndex } = location.state
      setPanelId(panelId)
      setPanelIndex(panelIndex)
      localStorage.setItem('myState', JSON.stringify({ panelId, panelIndex }))
      return
    }
    // 路由状态不存在则读取缓存
    const cachedState = localStorage.getItem('myState')
    if (!cachedState) {
      // 无缓存时跳转回父页面,避免空屏
      navigate('/')
      return
    }
    try {
      const parsedState = JSON.parse(cachedState)
      setPanelId(parsedState.panelId)
      setPanelIndex(parsedState.panelIndex)
    } catch (err) {
      localStorage.removeItem('myState')
      navigate('/')
    }
  }, [location.state, navigate])

  // 原有逻辑不变
}

注意事项

如果你需要在点击Link跳转前就用到panelId和panelIndex,不需要从localStorage读取,SettingMenu组件的props本身就传入了panelId和panelIndex,直接使用即可。

内容的提问来源于stack exchange,提问作者kim tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:54:03