React使用React Router获取路径参数时出现props未定义错误
问题解决:React Router v6 获取路径参数报错
错误原因
- 函数组件中误用了
this.props,函数组件不存在this上下文,直接访问会触发Cannot read property 'props' of undefined错误。 - React Router v6 已不再通过组件props传递
match对象,原props.match.params的写法完全失效,需使用专属钩子获取路径参数。 - 路由路径定义的参数名是
userId(/profile/:userId),但代码中错误使用了id,参数名不匹配导致无法正确取值。
修复步骤
1. 导入useParams钩子
在Profile.js顶部导入React Router提供的useParams钩子:
import { useParams } from 'react-router-dom';
2. 获取路径参数
在Profile组件内部调用useParams,提取对应参数:
export const Profile = () => { const { userId } = useParams(); // 对应路由路径中的:userId参数 // ... 其他代码 }
3. 修正数据请求逻辑
替换getUserProfileInformation函数中错误的参数获取方式,同时优化async/await写法(避免async函数内混用then,提升代码可读性):
const getUserProfileInformation = async () => { try { const response = await UserService.getUserProfileInformation(userId); const data = await response.json(); setUserProfileInformation(data); } catch (error) { console.error('加载用户信息失败:', error); } }
4. 优化useEffect依赖(可选但推荐)
将userId加入useEffect的依赖数组,确保当路径参数变化时,自动重新请求数据:
useEffect(() => { const fetchData = async () => { await getUserProfileInformation(); setLoading(false); }; fetchData(); }, [userId]);
完整修复后的Profile.js代码
import { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; export const Profile = () => { const [userProfileInformation, setUserProfileInformation] = useState([]); const [isLoading, setLoading] = useState(true); const { userId } = useParams(); useEffect(() => { const fetchData = async () => { await getUserProfileInformation(); setLoading(false); }; fetchData(); }, [userId]); const getUserProfileInformation = async () => { try { const response = await UserService.getUserProfileInformation(userId); const data = await response.json(); setUserProfileInformation(data); } catch (error) { console.error('加载用户信息出错:', error); } } if (isLoading) { return ( <div id="loading"> <h2>Loading...</h2> </div> ) } return ( <div> <div className="profileCard"> <h2>{userProfileInformation.email}</h2> </div> </div> ) }
内容的提问来源于stack exchange,提问作者devo9191
相关产品推荐
相关产品推荐

