React Router v6,使用钩子
在react-router-dom v6中,有一个名为的新钩子使用搜索参数 https://reactrouter.com/en/v6/hooks/use-search-params。所以与
const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")
你会得到"blablabla"
。请注意,searchParams 是 URLSearchParams 的一个实例,它也实现了一个迭代器,例如用于使用 Object.fromEntries 等。
React Router v4/v5,无钩子,通用
React Router v4 不再为你解析查询,但你只能通过以下方式访问它this.props.location.search
(或使用位置,见下文)。原因参见恩博查特的回答 https://stackoverflow.com/a/48256676/969483.
例如。和qs https://github.com/ljharb/qs库导入为qs
你可以做
qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
另一个图书馆是请求参数 https://github.com/sindresorhus/query-string. See 这个答案 https://stackoverflow.com/a/53079875/969483有关解析搜索字符串的更多想法。如果您不需要IE兼容 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams你也可以使用
new URLSearchParams(this.props.location.search).get("__firebase_request_key")
对于功能组件,您将替换this.props.location
用钩子使用位置 https://reacttraining.com/react-router/core/api/Hooks/uselocation。注意,你可以使用window.location.search
,但这不允许在更改时触发 React 渲染。
如果您的(非功能性)组件不是Switch
你需要使用带路由器 https://reacttraining.com/react-router/web/api/withRouter访问路由器提供的任何道具。
反应路由器 v3
React Router 已经为你解析了位置并将其传递给你的路由组件 https://reacttraining.com/react-router/core/api/Route/Route-props作为道具。您可以通过以下方式访问查询(网址中?之后)部分
this.props.location.query.__firebase_request_key
如果您正在查找路由器内用冒号 (:) 分隔的路径参数值,可以通过以下方式访问这些值
this.props.match.params.redirectParam
这适用于最新的 React Router v3 版本(不确定是哪个)。据报告使用较旧的路由器版本this.props.params.redirectParam
.
General
nizam.sp 的建议
console.log(this.props)
无论如何都会有帮助。