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

React详情页Fetch未发起请求导致返回Null问题求助

问题排查:详情页Fetch未发起请求导致返回Null

问题描述

已实现从API获取商品列表并渲染,点击商品通过Link跳转至详情页(路径/products/honey/:id),但进入详情页后Fetch未发起任何请求,最终返回Null。接口在Swagger测试正常,已排除CORS问题(列表页请求正常),替换localhost为Docker容器名称也无效。

相关代码

路由配置(App.tsx)

<Route path='/products/honey/:id' element={<Honey />} />

商品列表页代码

{items.map((item) => (
  <Link
    to={`/products/honey/${item.id}`}
    style={{ textDecoration: 'none' }}
  >
    <div>
      <div key={item.id} className={styles.item}>
        <img src={item.img_url} />
        <h1>{item.item_name}</h1>
        <h3>{item.price} руб.</h3>
        <button>В корзину</button>
      </div>
    </div>
  </Link>
))}

详情页模板代码(原代码)

const {id} = useParams<{id: string}>();
const [error, setError] = useState(null)
const [result, setResult] = useState(null)
const [isLoaded, setIsLoaded] = useState(false)
const [item, setItem] = useState<item | null>(null);
useEffect(() => {
        fetch(`http://localhost:8000/items/by_id/${id}`)
            .then((res) =>
                res.json()
            )
            .then(
                data => {
                    setResult(data)
                    setItem(data)
                    console.log(item)
                },
                (error) => {
                    setIsLoaded(true)
                    setError(error)
                }
            )

    }, [id])

排查与解决方案

1. 确认useParams是否正确获取到ID

  • 在useEffect开头添加console.log('当前ID:', id),检查ID是否为undefined。如果ID未正确获取,会导致请求URL无效,甚至不发起请求。
  • 优化解构逻辑,避免id为undefined:
    const { id } = useParams<{ id: string }>() || {};
    

2. 完善Fetch的错误处理与请求触发条件

  • 仅当id存在时才发起请求,避免无效调用;添加catch捕获所有请求错误(包括res.json()解析失败的情况);修正console.log的内容(useState是异步更新,直接打印item会显示旧值,应打印data)。

修改后的useEffect代码:

useEffect(() => {
  if (!id) return; // ID不存在则不发起请求

  setIsLoaded(false);
  setError(null);

  fetch(`http://localhost:8000/items/by_id/${id}`)
    .then((res) => {
      if (!res.ok) throw new Error(`请求失败:${res.status}`);
      return res.json();
    })
    .then((data) => {
      setResult(data);
      setItem(data);
      console.log('获取到的商品详情:', data);
    })
    .catch((error) => {
      setError(error.message);
      console.error('请求错误:', error);
    })
    .finally(() => {
      setIsLoaded(true);
    });
}, [id]);

3. 检查组件渲染与路由匹配

  • 在Honey组件的最顶部添加console.log('Honey组件已渲染'),确认进入详情页时组件是否正常挂载。
  • 检查是否存在路由冲突,比如父路由是否设置了/products/honey且没有添加end属性,导致优先匹配父路由而非带参数的详情路由。如果有,修改父路由:
    <Route path='/products/honey' element={<HoneyList />} end />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:07:50