React.js 如何为/profile路径添加currentUser.id?路由不生效
配置错误定位与修改方案
错误1:路由定义未声明动态参数
你当前App组件内的个人中心路由配置为:
<Route path="/profile" component={Profile} />
未添加:id动态占位符,无法匹配带参数的路径。
修改方式
替换为如下配置:
<Route path="/profile/:id" component={Profile} />
注意:不要为该路由添加exact属性,避免阻断带参路径的匹配
错误2:跳转链接未拼接用户ID
你当前Navbar组件内的个人中心跳转链接为写死的固定路径:
<Link to={'/profile' } className='btn-link' >
未将currentUser.id拼接到路径末尾,跳转后URL自然不会携带用户ID。
修改方式
将to属性改为模板字符串拼接动态ID:
<Link to={`/profile/${currentUser.id}`} className='btn-link' >
补充:在Profile组件中读取路由参数
如果需要通过路径参数调用后端接口获取用户数据,可使用react-router-dom提供的useParams钩子提取ID:
import { useParams } from 'react-router-dom'; function Profile() { // 直接获取URL中携带的id参数 const { id } = useParams(); // 后续可使用id请求对应接口 }
内容的提问来源于stack exchange,提问作者Lee Soon Fatt
相关产品推荐
相关产品推荐

