在React搭建的SPA項目中頁面的title是直接寫在入口index.html中,當路由在切換不用頁面時,title是不會動態變化的。那麼怎麼讓title隨着路由的切換動態變化呢?
1.在定義路由時增長title屬性。html
{ path: "/regularinvestment", component: Loadable({ loader: () => import('./../../business/Regularinvestment/index'), loading: PageLoading }), title: "這是自定義的標題" }
2.在路由的index.js獲取到自定義的title設置頁面標題便可。code
const RouteWithSubRoutes = route => { return ( <Route exact path={route.path} render={props => { document.title = route.title || "默認title"; return <route.component {...props} routes={route.routes}></route.component> }} /> ); }; export default () => { return allRouters.map((route, i) => { return <RouteWithSubRoutes key={i} {...route}/> }) };