有两种方法可以做到这一点:
1)location.search
在 react 组件中使用获取查询字符串,然后将其传递给子组件以防止重新渲染整个组件。React-router 有关于这个的官方例子。
2)定义router的正则表达式路径来捕获查询字符串,然后将其传递给react组件。以分页为例:
route.js,对于路由器配置,你可以参考这个
const routerConfig = [
{
path: '/foo',
component: 'Foo',
},
{
path: '/student/listing:pageNumber(\\?page=.*)?',
component: 'Student'
},
学生.js
render() {
// get the page number from react router's match params
let currentPageNumber = 1;
// Defensive checking, if the query param is missing, use default number.
if (this.props.match.params.pageNumber) {
// the match param will return the whole query string,
// so we can get the number from the string before using it.
currentPageNumber = this.props.match.params.pageNumber.split('?page=').pop();
}
return <div>
student listing content ...
<Pagination pageNumber = {currentPageNumber}>
</div>
}
分页.js
render() {
return <div> current page number is {this.props.pageNumber} </div>
}
第二种解决方案更长但更灵活。用例之一是服务器端渲染:
除了react组件外,应用程序的其余部分(例如预加载的 saga)需要知道包含查询字符串的 url 以进行 API 调用。