react.js - React-Router v4 中 match 对象的 params 是如何匹配的
本文介绍了react.js - React-Router v4 中 match 对象的 params 是如何匹配的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<ConnectedRouter history={history}>
<div>
<NewsHeader />
<Switch>
<Route path="/:page?" component={NewsList} />
<Route path="/new/:page?" component={NewsList} />
<Route path="/show/:page?" component={NewsList} />
<Route path="/ask/:page?" component={NewsList} />
<Route path="/jobs/:page?" component={NewsList} />
</Switch>
</div>
</ConnectedRouter>
当 URL 是 http://localhost:3000/1 时,params 如下图:
当 URL 是 http://localhost:3000/new/1 时,params 如下图:
但是文档中对 params 的描述是这样的:
params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
我的理解是 params 是 URL 中动态部分获得的键值对,上面两个 URL 获得的 params 都应该是 { page: "1" }
才对,是哪里有问题呢?
解决方案
实质上你的http://localhost:3000/1和http://localhost:3000/new/1都匹配的是
<Route path="/:page?" component={NewsList} />
它使用的是如下的path匹配
https://github.com/pillarjs/p...
不同的是react-router默认设置为模糊匹配(options中的end为false),所以应该
<Route exact path="/:page?" component={NewsList} />
这篇关于react.js - React-Router v4 中 match 对象的 params 是如何匹配的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文