題目描述react-router 嵌套路由元素,子元素的相關內容加載不出來,而且整個地址無法匹配題目來源及自己的思路想用外層路由實現模板頁、登錄、404等頁面,在模板頁內層用子路由實現內容的動態加載相關代碼// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)//外層路由 App.jsrender() {
return ( <Switch>
<Route exact component={Home} path="/" />
<Route component={Login} path="/login" />
<Route component={NotFound} />
</Switch>
)
}//內層Home.jsrender() {
return ( <Layout>
<Header>Some Info.</Header>
<Content>
<Switch>
<Route exact path="/" component={MyLayout} />
<Route path="/temperature/month" component={TemperatureMonth} />
<Route path="/temperature/day" component={TemperatureDay} />
</Switch>
</Content>
</Layout>
);
}你期待的結果是什么?實際看到的錯誤信息又是什么?輸入http://127.0.0.1:3000/temperature/month,結果匹配到外層NotFound.
1 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
因為使用Switch標簽包裹,route只會被渲染一個,/temperature/month 這個路由在App.js并沒有匹配,所以就渲染了<Route component={NotFound} />。
為什么沒有匹配 <Route exact component={Home} path="/" /> 這個? 因為是精準匹配,所以導致/temperature/month 無法匹配到這個組件。
如何解決?
1.調整一下Route順序,去掉精準匹配,讓/temperature/month匹配到Home組件
<Route component={Login} path="/login" /> <Route component={Home} path="/" /> <Route component={NotFound} />
添加回答
舉報
0/150
提交
取消