我使用Route组件上的render属性或使用withRouter中的HOC接收的匹配对象始终生成错误的匹配对象。位置对象是正确的。匹配网址属性始终为'/'
这是一个显示问题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'))
单击关于链接(主题有相同的问题):注意使用Route render的AddressBar,在顶部始终显示
> Match: /
在屏幕底部,Component显示正确的match.url
Match: /about
我做错了什么?如何在AddressBar中获得有效的匹配对象?
这是我用于特定路线的丑陋黑客,我需要知道具体的'联盟'参数。
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]);
答案 0 :(得分:0)
如果我正确理解您的问题,您可以使用React Router的匹配工具从URL中提取参数。这对我有用
import { matchPath } from 'react-router'
const match = matchPath('/users/123', {
path: '/users/:id',
exact: true,
strict: false
})
答案 1 :(得分:0)
我想每当需要使用match时,还需要将其与路径名结合起来
示例
var match = this.props.match;
<Link className = 'xxx' to = {{pathname:match.url + '/target'}}