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

从localStorage读取过滤短语数组时遇双错误的技术求助

问题解决方法

错误原因分析

  1. ReferenceError: localStorage is not defined:在服务端渲染(SSR)环境中,window对象不存在,直接访问localStorage会触发该错误。
  2. Cannot read properties of null (reading 'filter'):你给useState的初始值在服务端时是null,而null没有filter方法;同时在客户端时你赋值的是getPhraseArr函数本身,而非调用函数后的结果。

修正方案

方案一:修正useState初始值

直接确保初始状态始终是数组类型,避免null或函数赋值:

const getPhraseArr = () => {
  const arr_of_phrases = localStorage.getItem('arr_of_phrases')
  // 优化:直接用已获取的变量,避免重复调用localStorage.getItem
  return arr_of_phrases ? JSON.parse(arr_of_phrases) : []
}

const [phraseArr, setPhraseArr] = useState(
  // 客户端调用函数获取数据,服务端直接返回空数组
  typeof window !== 'undefined' ? getPhraseArr() : []
)

方案二:使用useEffect在客户端挂载后获取(更推荐SSR场景)

useEffect仅在客户端执行,彻底避免服务端访问localStorage的问题:

const [phraseArr, setPhraseArr] = useState([])

useEffect(() => {
  const getPhraseArr = () => {
    const arr_of_phrases = localStorage.getItem('arr_of_phrases')
    return arr_of_phrases ? JSON.parse(arr_of_phrases) : []
  }
  setPhraseArr(getPhraseArr())
}, [])

过滤代码的额外优化

为了更严谨,可增加collection.id的存在性判断,避免因collection.id为空导致的逻辑错误:

const { phraseApp } = useContext(AppContext)

// 先判断collection.id是否存在,再执行过滤
const scoreArr = collection.id 
  ? phraseArr.filter(i => i.substring(0, i.indexOf('_')) === collection.id)
  : []
const colScore = scoreArr.length

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:50:25