React项目中想在不同的路由页面都有自己的独立title,并且统一设置。
可以在每个路由页面的 componentDidMount() 钩子回调中 document.title = ‘title’ 来设置,但是这样太麻烦,每个路由页面都需要单独设置
于是,研究出一种更好的方式,在Index.js 入口处统一设置 document.title = ‘title’:
我的项目是把路由和设置独立写的,方便管理,以及其他权限功能等等。
routes.js
import Index from "../pages/Index";
import Home from '../pages/Home/Index'
import Classify from '../pages/Home/Classify'
import ShoppingCart from '../pages/Home/ShoppingCart'
let routes = [
{
path: '/Index',
component: Index,
meta:{
title:'商城首页'
}
},
{
path:'/Home',
component:Home,
meta:{
title:'主页'
},
children:[
{
path:'/Home/Classify',
component:Classify,
meta:{
title:'商品分类'
},
},
{
path:'/Home/ShoppingCart',
component:ShoppingCart,
meta:{
title:'购物车'
},
}
]
}
]
export default routes
index.js 入口文件:
import React from 'react';
import ReactDOM from 'react-dom'
import routes from './router/routes'
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
import App from "./App";
import { Provider } from 'react-redux'
利用 document.title 在每个Route路由文件设置
这里不推荐使用 onEnter 钩子函数设置,此API在react-router 4.0 被废弃了
设置title效果图: