且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React - 如何从查询字符串中获取参数值?

更新时间:2023-02-24 08:40:10

React Router v4 和 React Router v5,通用

React Router v4 不再为您解析查询,但您只能通过 this.props.location.search(或 useLocation,见下文)访问它.原因参见 nbeuchat 的回答.

React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search (or useLocation, see below). For reasons see nbeuchat's answer.

例如使用 qs 库作为 qs 导入,你可以做

E.g. with qs library imported as qs you could do

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key

另一个库是 query-string.有关解析搜索字符串的更多想法,请参阅此答案.如果您不需要IE 兼容性,您也可以使用

Another library would be query-string. See this answer for some more ideas on parsing the search string. If you do not need IE-compatibility you can also use

new URLSearchParams(this.props.location.search).get("__firebase_request_key")

对于功能组件,您可以将 this.props.location 替换为钩子 使用位置.请注意,您可以使用 window.location.search,但这将不允许在更改时触发 React 渲染.如果您的(非功能性)组件不是 Switch 的直接子级,您需要使用 withRouter 访问任何路由器提供的道具.

For functional components you would replace this.props.location with the hook useLocation. Note, you could use window.location.search, but this won't allow to trigger React rendering on changes. If your (non-functional) component is not a direct child of a Switch you need to use withRouter to access any of the router provided props.

React Router v3

React Router 已经为您解析了位置并将其传递给您的 RouteComponent 作为道具.您可以通过

React Router already parses the location for you and passes it to your RouteComponent as props. You can access the query (after ? in the url) part via

this.props.location.query.__firebase_request_key

如果您要查找路由器内部以冒号 (:) 分隔的路径参数值,可以通过以下方式访问这些值

If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via

this.props.match.params.redirectParam

这适用于较晚的 React Router v3 版本(不确定是哪个).据报道,较旧的路由器版本使用 this.props.params.redirectParam.

This applies to late React Router v3 versions (not sure which). Older router versions were reported to use this.props.params.redirectParam.

一般

nizam.sp 的建议去做

nizam.sp's suggestion to do

console.log(this.props)

在任何情况下都会有所帮助.

will be helpful in any case.