location对象正确。匹配url属性始终为'/‘
这是一个显示problem React Router 4 match woes的代码笔
const { render } = ReactDOM
const {
HashRouter,
Route,
Link
} = ReactRouterDOM
const App = () => (
<HashRouter>
<div>
<AddressBar/>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</HashRouter>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = ({ match }) => (
<div>
<h2>About</h2>
<h3>Match: {match.url}</h3>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li><Link to={`${match.url}/rendering`}>Rendering with React</Link></li>
<li><Link to={`${match.url}/components`}>Components</Link></li>
<li><Link to={`${match.url}/props-v-state`}>Props v. State</Link></li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
<h3>Match: {match.url}</h3>
</div>
)
const AddressBar = () => (
<Route render={({ location: { pathname }, match: {url}, goBack, goForward }) => (
<div className="address-bar">
<div>
<button
className="ab-button"
onClick={goBack}
>◀︎</button>
</div>
<div>
<button
className="ab-button"
onClick={goForward}
>▶</button>
</div>
<div className="url">URL: {pathname} Match: {url}</div>
</div>
)}/>
)
render(<App/>, document.getElementById('root'))单击About链接(主题也有同样的问题):请注意,使用路由渲染的AddressBar始终显示在顶部
> Match: /Match: /about
我做错了什么?
let keys = []
let path = '/*/:league/:id';
if (this.path.split('/').length === 3)
path = '/*/:league';
let re = pathToRegexp(path, keys);
const result = re.exec(this.path)
if (result && result[2])
this.store.setLeague(result[2]);发布于 2017-08-15 05:19:55
如果我正确理解了您的问题,您希望能够使用React Router的匹配工具从URL中提取参数。这对我很有效
import { matchPath } from 'react-router'
const match = matchPath('/users/123', {
path: '/users/:id',
exact: true,
strict: false
})发布于 2018-06-29 21:43:44
我想当你需要使用匹配的时候,你也需要把它和路径名结合起来
示例
var match = this.props.match;
<Link className = 'xxx' to = {{pathname:match.url + '/target'}}https://stackoverflow.com/questions/44233514
复制相似问题