向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
相关产品推荐
相关产品推荐

