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

React路由使用容器组件时props.match.params为undefined如何解决

问题根因

react-router 中match、location、history这三类路由属性,只会自动注入给直接注册在路由component属性上的组件。你现在把VideoPlayerContainer注册为路由组件,所以只有容器组件能拿到路由props,你没有将相关属性传递给内部的VideoPlayer组件,才会导致VideoPlayer读取props.match时报错。

解决方案

方案1:路由props透传

修改VideoPlayerContainer组件,接收路由props后传递给VideoPlayer:

export default function VideoPlayerContainer(props) {
  return (
    <React.Fragment>
      <div>
        <PublicNav />
        {/* 全量透传路由props,也可以按需只传`match`或者单独提取`videoId`传递 */}
        <VideoPlayer {...props} />
      </div>
    </React.Fragment>
  );
}  

方案2:使用useParams Hook(react-router v5+ 支持)

不需要修改容器组件,直接在VideoPlayer中使用官方提供的Hook读取路由参数,避免props逐层传递的问题:
首先从react-router-dom引入useParams,然后修改参数读取逻辑:

import { useParams } from 'react-router-dom';
import { useState } from 'react';

export default function VideoPlayer() {
  const classes = useStyles();
  // 直接从路由中提取videoId参数,不需要依赖props
  const { videoId } = useParams();
  const [video, setVideo] = useState([]);
  const [CommentLists, setCommentLists] = useState([]);

  const videoVariable = {
    videoId: videoId,
  };
  // 后续原有逻辑保持不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:36:01