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

向React组件传递数据时出现Undefined报错如何解决

问题原因分析
  • 路由属性注入失效:只有被React Router的<Route>组件直接匹配渲染的组件,才能默认拿到match/location/history这类路由专属属性。你在front.layout.js里是手动调用<Profile />组件,没有通过Route渲染,也没有手动传递match属性,所以props.match是undefined,访问params自然触发报错。
  • 跨组件传参取值错误:你给Profile组件传递的属性名是values,但你目前的Profile组件代码里完全没有接收props.values的逻辑,自然拿不到传输的user数据。
解决方法

场景1:Profile组件不需要获取路由params,只需要用父组件传的user数据

直接删掉Profile里访问props.match.params的相关代码,改为接收values属性即可:

// index.js
import Layout from "../../Components/layouts/front.layout";

const Profile = (props) => {
    // 接收父组件传递的user数据
    const user = props.values;
    // 后续业务逻辑直接操作user变量即可
    // ...
}

场景2:Profile组件同时需要路由params和父组件传的user数据

方式1:给手动渲染的Profile传递match属性

如果父组件front.layout.js本身是路由组件,可以拿到match属性,直接透传给Profile即可:

// front.layout.js
import Profile from '../../Views/profile'

const [user, setUser] = useState({});

 return (
    <>
       {/* 透传父组件的match属性给Profile */}
       <Profile values={user} match={props.match} />
    </>
 )

方式2:用React Router Hook获取路由参数(更推荐)

如果使用React Router v5及以上版本,直接用内置Hook拿路由参数,不需要依赖props注入,适配性更强:

// index.js(React Router v6版本写法)
import { useParams } from 'react-router-dom';
import Layout from "../../Components/layouts/front.layout";

const Profile = (props) => {
    // 用Hook直接获取路由params,不需要从props取
    const params = useParams();
    // 接收父组件传的user数据
    const user = props.values;
    // 后续业务逻辑
    // ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:48:02