[英]Wrapping application routes for children with React-Router-4
當使用 react-router(版本 3)時,我能夠創建嵌套路由,因為包裝器組件接收了子組件。 通過這種方式,我能夠為根組件使用“全局”減速器,因為每個子組件都有自己的減速器:
<Provider store={store}>
<Router key={Math.random()} history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={MainPage}/>
<Route path="mainPage" component={MainPage}/>
<Route path="secPage" component={SecPage}/>
<Route path="*" component={MainPage}/>
</Route>
</Router>
</Provider>
在根組件內部:
render() {
return (
<div className="app-wrapper">
{this.props.children}
</div>
);
}
我將路由器升級為使用版本 4:
<Provider store={store}>
<Router history={history}>
<div>
<Route exact path="/" component={MainPage}/>
<Route path="secPage" component={SecPage}/>
<Route path="mainPage" component={MainPage}/>
</div>
</Router>
</Provider>
正如你所看到的——我的路由現在是“Flat”,所以我不能真正使用根組件,因此需要為每個組件使用“globalReducer”。
如何使用與以前相同的方法? 或者至少是接近它的東西?
剛剛找到了解決方案-用根組件包裝子路由:
<Provider store={store}>
<Router history={history}>
<App>
<Route exact path="/" component={MainPage}/>
<Route path="mainPage" component={MainPage}/>
<Route path="secPage" component={SecPage}/>
</App>
</Router>
</Provider>
布局組件。
const DefaultLayout = ({ children }) => {
return (
<>
<main id="mainWrapper">
{children}
</main>
</>
);
};
export default DefaultLayout;
react-router-dom
v5
<Switch>
<DefaultLayout>
<Route exact path="/" component={MainPage}/>
<Route path="mainPage" component={MainPage}/>
<Route path="secPage" component={SecPage}/>
</DefaultLayout>
<AuthLayout>
<Route path="login" component={Login}/>
</AuthLayout>
</Switch>
``
```react-router-dom``` **v6**
```js
<Router>
<Routes>
<Route exact path="/" element={<DefaultLayout><MainPage/></DefaultLayout>} />
<Route path="mainPage" element={<DefaultLayout><MainPage/></DefaultLayout>} />
<Route path="SecPage" element={<DefaultLayout><SecPage/></DefaultLayout>} />
<Route path="Login" element={<AuthLayout><Login/></AuthLayout>} />
</Routes>
</Router>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.