如何在我的路由中定义路由。jsx文件捕获__firebase_request_key参数值从一个URL生成的Twitter的单点登录过程后,从他们的服务器重定向?
http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
我尝试了以下路由配置,但:redirectParam没有捕获提到的参数:
<Router>
<Route path="/" component={Main}>
<Route path="signin" component={SignIn}>
<Route path=":redirectParam" component={TwitterSsoButton} />
</Route>
</Route>
</Router>
从v4开始,React路由器不再直接在其location对象中提供查询参数。原因是
There are a number of popular packages that do query string
parsing/stringifying slightly differently, and each of these
differences might be the "correct" way for some users and "incorrect"
for others. If React Router picked the "right" one, it would only be
right for some people. Then, it would need to add a way for other
users to substitute in their preferred query parsing package. There is
no internal use of the search string by React Router that requires it
to parse the key-value pairs, so it doesn't have a need to pick which
one of these should be "right".
包含了这个之后,只解析location会更有意义。在需要查询对象的视图组件中搜索。
你可以通过覆盖react-router中的withRouter来实现这一点
customWithRouter.js
import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';
const propsWithQuery = withPropsOnChange(
['location', 'match'],
({ location, match }) => {
return {
location: {
...location,
query: queryString.parse(location.search)
},
match
};
}
);
export default compose(withRouter, propsWithQuery)
我花了很长时间才解决这个问题。如果以上都不行,你可以试试这个。我正在使用创建-反应应用程序
需求
react-router-dom ^ 4.3.1“:
解决方案
在指定路由器的位置
<Route path="some/path" ..../>
像这样添加您想要传入的参数名
<Route path="some/path/:id" .../>
在你渲染一些/路径的页面上,你可以指定这个来查看参数名调用id,就像这样
componentDidMount(){
console.log(this.props);
console.log(this.props.match.params.id);
}
在导出默认值的最后
export default withRouter(Component);
记住要包含import
import { withRouter } from 'react-router-dom'
当console.log(this.props)时,你就可以知道传递了什么。玩得开心!
在typescript中,参见下面的示例片段:
const getQueryParams = (s?: string): Map<string, string> => {
if (!s || typeof s !== 'string' || s.length < 2) {
return new Map();
}
const a: [string, string][] = s
.substr(1) // remove `?`
.split('&') // split by `&`
.map(x => {
const a = x.split('=');
return [a[0], a[1]];
}); // split by `=`
return new Map(a);
};
在react中使用react-router-dom,你可以做
const {useLocation} from 'react-router-dom';
const s = useLocation().search;
const m = getQueryParams(s);
参见下面的例子
//下面是上面转换和缩小的ts函数
如果(const getQueryParams = t = > {! t | |“字符串”!=typeof t||t.length<2)return new Map;const r=t.substr(1).split("&")。地图(t = > {const r = t.split(" = ");返回[r[0],[1]]});返回新地图(r)};
//一个示例查询字符串
Const s = '?__arg1 = value1&arg2 = value2 '
getQueryParams(s)
console.log (m.get (__arg1))
console.log (m.get(最长))
Console.log (m.t get('arg3')) //不存在,返回undefined