![](/img/trans.png)
[英]react , how can i render multiple components in single route in react-router-dom v6?
[英]React-router-dom: Render two components under one route
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route
path="/test/:id"
component={Question1} />
<Route
path="/test/:id"
component={Question2} />
</div>
</BrowserRouter>
</Provider>
我需要從ID為1的Question1導航到應該為ID 2的Question2。我可以從測試無問題地導航至Question1,但是當我想對使用this.props.history.push('/test/2')
,URL更改了,但我沒有導航到問題2。
有任何想法嗎 ?
您應該有一個單獨的Question
組件,該組件可以處理id
並顯示適當的問題。
您可以使用Route
的render
方法執行相同的操作
<Route
path="/test/:id"
render={(props)=>{
switch(props.match.params.id){
case "1": return <Question1/>;
case "2" : return <Question2/>;
default : return null;
}
}}
/>
編輯 :注釋后已更正代碼
您可以使用一條路線來完成此任務,然后在組件中加載正確的問題:
<Route path="/test/:id" component={Question} />
// Question.js
export default React.createClass({
render() {
return (
<div>
<h2>Question {this.props.params.id}</h2>
</div>
)
}
})
doc: 帶參數的路線
問題是在這種情況下, <Switch>
將與<BrowserRouter/>
下的第一個組件匹配。 如果它與第一個路徑不匹配,它將嘗試第二個。 這就是Switch
工作方式。 因此,在您的示例中, path=/test/:id
的路徑模板實際上與/test/1
和/test/2
都匹配,並且Route
始終呈現Question1
而從不呈現Question2
。 在https://reacttraining.com/react-router/web/api/Switch上查看文檔。
您可以做的一件事是,如果您知道只有兩個Question
那么您可以做
<Route exact
path="/test/1"
component={Question1}
/>
<Route exact
path="/test/2"
component={Question2}
/>
它將立即解決您的問題,但是我不建議您這樣做,因為當您收到更多Question
,它會變得不合理。 @palsrealm建議采用更好的設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.