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

React中无法将localStorage数据存入state对象数组的解决方案

React localStorage数据无法写入组件State问题修复

你的代码存在3个直接导致问题的错误:

  • Key名拼写不匹配:存储localStorage时用的key是data,读取时错写为dati,根本无法命中之前存储的内容
  • 异步时序错误:sendGetRequest是异步请求方法,你调用后没有等待请求完成、数据写入localStorage,就立刻执行读取逻辑,此时localStorage里还没有存入接口返回的数据
  • 未执行State更新操作:你只是把处理后的列表打印到了控制台,没有调用React的setState方法把处理好的数据写入组件状态,自然state里的data数组不会有内容

修正后完整代码

async sendGetRequest(){
  try {
    const res = await axios.get('https://nba-players.herokuapp.com/players-stats')
    // 统一key名存储本地缓存
    localStorage.setItem('data', JSON.stringify(res.data))
    // 接口返回后直接处理前10条数据
    const playerList = res.data.slice(0, 10).map(item => ({
      nome: item.name,
      team: item.team_name
    }))
    // 写入组件state
    this.setState({
      data: playerList
    })
  } catch (err) {
    console.log('请求异常:', err)
    // 请求失败兜底:读取本地已有缓存渲染
    const localCache = localStorage.getItem('data')
    if (localCache) {
      const cacheResult = JSON.parse(localCache)
      const playerList = cacheResult.slice(0, 10).map(item => ({
        nome: item.name,
        team: item.team_name
      }))
      this.setState({
        data: playerList
      })
    }
  }
}

componentDidMount(){
  this.sendGetRequest()
}

额外注意事项

  • 异步逻辑不要混用async/await和.then()链式写法,选一种统一使用,避免时序混乱
  • 所有依赖异步返回结果的逻辑,必须放到await之后或者请求回调内部执行,不要在发起异步请求后立刻同步执行
  • React类组件更新状态必须调用setState方法,直接给state属性赋值不会触发视图更新,也不会生效
  • 遍历数组前建议加非空判断,避免接口异常、缓存不存在时直接读取数组下标导致代码报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 19:09:52