React Router v4含查询参数的路由匹配失效问题咨询
解决React Router v4路由匹配异常的问题
嘿,我一眼就看出问题所在啦!React Router v4的<Route>组件的path属性只负责匹配URL的路径部分,也就是/change-password/这一段,而问号后面的resetToken=123属于查询参数(query params),根本不会被包含在path的匹配逻辑里。你把查询参数写在path里的写法是错误的,这就是组件无法渲染的原因。
下面给你正确的解决步骤:
1. 修正Route的path配置
把path改成只包含路径部分就行,不用管查询参数:
<Route path='/change-password' component={ChangePassword} />
(注:要不要末尾的斜杠都可以,React Router会自动处理这种细微差异)
2. 在组件中获取查询参数
React Router v4不再自动解析查询参数到location.query了,不过我们可以用浏览器原生的URLSearchParams API来轻松获取resetToken的值:
如果你用的是函数组件:
import { useLocation } from 'react-router-dom'; function ChangePassword() { const location = useLocation(); // 解析resetToken参数 const resetToken = new URLSearchParams(location.search).get('resetToken'); return <h1>Testing, your reset token is: {resetToken}</h1>; }
如果是类组件:
需要用withRouter高阶组件来注入location属性:
import React from 'react'; import { withRouter } from 'react-router-dom'; class ChangePassword extends React.Component { render() { const resetToken = new URLSearchParams(this.props.location.search).get('resetToken'); return <h1>Testing, your reset token is: {resetToken}</h1>; } } // 用withRouter包装组件,获取路由相关属性 export default withRouter(ChangePassword);
这样配置后,当你访问http://localhost:3000/change-password/?resetToken=123时,组件就能正常渲染,并且能正确拿到resetToken的值啦。
内容的提问来源于stack exchange,提问作者Jenny Mok
相关产品推荐
相关产品推荐

