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

React页面刷新报错TypeError: articles[articles.length-1] is undefined如何解决

问题根源

你App组件里articles的初始值是空数组,组件首次渲染时会直接把空数组传给ArticlesList,此时articles.length为0,articles[0-1]也就是articles[-1]本质是undefined,访问undefined的img属性自然会抛出类型错误。后续fetch请求拿到数据更新articles后才会触发二次渲染,这时候数组长度足够才不会报错,所以你修改代码不刷新时能正常运行。

解决方法

方案1:组件渲染前加长度判断

在ArticlesList组件最外层加判断,数组长度不足3时显示加载占位,避免直接访问不存在的下标:

const ArticlesList = ({ articles }) => {
  // 长度不足时显示加载状态
  if (articles.length < 3) return <div>加载中...</div>
  
  return (
    // 原有代码保持不变
  )
}

方案2:给图片src加可选链和默认值

不想加加载状态的话,可以直接在访问属性时用可选链兜底,避免报错:

<img
  className="d-block w-100"
  src={articles[articles.length-1]?.img || ''}
  alt="First slide"
  width="1100" height="400"
/>

剩下两个轮播项的src属性也做同样的修改即可。

方案3:父组件增加加载状态

在App组件里加loading状态,请求未完成时不渲染ArticleList:

function App() {
  const [articles, setArticles] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const getArticles = async () =>{
      const articlesFromServer = await fetchArticles()
      setArticles(articlesFromServer)
      setLoading(false)
    }
    getArticles()
  }, [])

  // 原有fetch逻辑保持不变

  return (
    <Router>
      <>
      <Header />
      <Route path='/' exact render={(props) => (
        <>
          {loading ? <div>加载中...</div> : <ArticleList articles={articles} />}
        </>
      )} />
      <Route path='/details/:id' exact component={ArticleDetails} />
      </>
    </Router>
  );
}

三种方案选任意一种都可以解决报错问题,如果你希望页面显示更连贯,推荐用方案3配合占位骨架屏,体验更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:01