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

ReactJS中通过URL的ID匹配数据列表,页面空白问题排查

React博客单文章页面空白问题解决方案

页面空白的核心原因有两个:

  1. 组件初始状态blog为null,直接访问blog.title/blog.content会触发Cannot read properties of null错误,导致组件渲染失败
  2. useEffect的依赖数组为空,当URL中的id变化时,不会重新执行数据查找逻辑,可能出现旧数据残留或无法获取新数据的情况

修正后的组件代码

import React, { useEffect, useState } from 'react'
import imgBien1 from '../../images/imgBien1.JPG'
import { ColumnSection, Section, SectionInterne, Column2, ContentWrapper2, Img, Column1,ContentWrapper, TopLine, Heading, Subtitle  } from './stockUnique'
import {useParams} from 'react-router-dom';
import { posts } from '../Data/data'

const StockUnique = () => {
  const { id } = useParams();
  const [blog, setBlog] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 重置状态,避免旧数据残留
    setLoading(true);
    setBlog(null);
    
    const parsedId = parseInt(id);
    // 校验id是否为有效数字
    if (!isNaN(parsedId)) {
      const foundBlog = posts.find(post => post.id === parsedId);
      setBlog(foundBlog);
    }
    setLoading(false);
  }, [id]); // 依赖数组添加id,id变化时重新执行数据查找

  // 加载状态提示
  if (loading) {
    return <div>加载中...</div>;
  }
  
  // 未找到文章的提示
  if (!blog) {
    return <div>未找到对应文章</div>;
  }
  
  return (
    <Section >
      <ColumnSection>
        <SectionInterne>
          <Column2>
            <ContentWrapper2>
              <Img src={imgBien1} alt='ok' />
            </ContentWrapper2>
          </Column2>
          <Column1>
            <ContentWrapper>
              <TopLine>{id}</TopLine>
              <Heading>{blog.title}</Heading>
              <Subtitle>{blog.content}</Subtitle>
            </ContentWrapper>
          </Column1>
        </SectionInterne>
      </ColumnSection>
    </Section>
  )
}

export default StockUnique

修改说明

  • 添加条件渲染:通过loading状态和blog存在性判断,避免数据未就绪或无匹配文章时触发渲染错误,同时给用户明确的状态反馈
  • 完善useEffect依赖:将id加入依赖数组,确保URL参数变化时重新执行数据查找逻辑
  • 增加参数校验:解析id后检查是否为有效数字,避免无效参数导致的查找错误
  • 状态重置:每次执行数据查找前重置blog和loading状态,避免旧数据干扰新请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:25:39