我使用Route組件上的render屬性或使用withRouter中的HOC接收的匹配對象始終會產生錯誤的匹配對象。位置對象是正確的。比賽url屬性始終是「/」反應路由器4,如何通過路由呈現或withRouter獲取有效的匹配url?
下面是一個代碼筆,顯示問題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'))
點擊關於鏈接(主題有同樣的問題):注意地址欄,它採用路由渲染,在上面總是顯示
> Match:/
,同時在屏幕底部的組件顯示正確的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]);
我有同樣的問題。你有沒有找到任何解決方法? – Voice
是的,我的工作很簡單。在我需要路線參數的地方,我只是自己解析路徑。 pathToRegexp已由路由器安裝。我有如下代碼。這是特定於我的路由,所以它很容易...你的里程可能會有所不同。我會在 – Pablo