Reactjs 将location.pathname响应为(自定义)标题

Reactjs 将location.pathname响应为(自定义)标题,reactjs,Reactjs,我目前正在开发一个react项目,我想在标题中显示当前页面标题。为此,我正在使用props.location.pathname和开关盒来获得所需的输出 这看起来像下面这样 var currentPathname = this.props.location.pathname; switch (currentPathname) { case '/': return 'Home'; } 路径的数量正在增加,我不想做一个大的切换案例。所

我目前正在开发一个react项目,我想在标题中显示当前页面标题。为此,我正在使用props.location.pathname和开关盒来获得所需的输出

这看起来像下面这样

    var currentPathname = this.props.location.pathname;

    switch (currentPathname) {
        case '/':
            return 'Home';
    }
路径的数量正在增加,我不想做一个大的切换案例。所以我想知道,是否有更好的方法根据路径设置(自定义)标题。我希望react路由器中会有可用的东西,但我还没有找到这样的东西


欢迎您提供任何见解。

我想说的是,您没有其他选择。您需要将路径映射到标题的位置(如果无法从路径名本身检索标题)。如果你想让它看起来短一点,你可以像这样使用三元运算符:

const path = this.props.location.pathname;
const title = path == '/' ? 'Home' : path == '/contact' ? 'customContactTitle' ...
你可以用它做一个钩子,比如“getTitle”,然后把它导入你的页面

我认为你的解决方案看起来很干净。只要将获取路径及其标题的逻辑分离到单个文件(hook)中,它就应该是可维护的,因为您通常不会太频繁地添加静态路径

如果您使用的是Next.js,那么您可以将路径及其对应的标题存储在数据库或CMS中,然后在构建期间(使用Next的getStaticProps)获取它们一次,如果这有助于提高可维护性的话


您是否考虑过使路径与标题相等或相关,这样您只需要在索引“/”页面上显示一次自定义标题,然后从路径中检索它?

使用映射而不是使用switch语句

const {pathname} = this.props.location;
const pathToTitleMap = {
  "/": "Home",
  "/something": "Amazing page title"
}
document.title = pathToTitleMap[pathname]

您可以拥有路径和标题的地图

const pathToTitleDictionary = {
    "/": "Home",
    "/about": "About",
    ...
}

function PageTitle({path}) {    
    useEffect(() => {
        document.title = pathToTitleDictionary[path];
    },[path]);
}

使用
更新标题

您可以通过维护类似JSON的

var titleForRoutes=[
{
route:"/",          //route 
title:"Home",       //title to show on header
component:HomePage  //React Component
},
{
route:"/Login",
title:"Login", 
component:LoginPage 
}
]
然后在routes中,通过迭代该Json来声明routed,另一方面,您可以使用相同的Json显示标题


谢谢。

我使用一个自定义元素来确保我的路径和标题整洁且彼此相邻。虽然比其他答案稍长一些,但它将所有内容都保留在属性中。可以通过使用
页面的功能组件来改进

<CustomRoute
    path="/path/is/here"
    component={ComponentHere}
    title="Title goes here"
/>

/* * * * * * * * * * * * * * */


export const CustomRoute = ({ component = null, title = null, ...props }) => {
  return (
    <Route
      {...props}
      render={
        props2 => <Page {...props2} component={component} title={title} />
      }
      key={props.path}
    />
  );
};

class Page extends Component {
  componentDidMount() {
    document.title =
      (this.props.title ? this.props.title + ' - ' : '') + 'Website Name';
  }

  render() {
    const { component, ...props } = this.props;
    const PageComponent = component;

    return <PageComponent {...props} />;
  }
}

/* * * * * * * * * * * * * * */
export const CustomRoute=({component=null,title=null,…props})=>{
返回(
}
key={props.path}
/>
);
};
类页面扩展组件{
componentDidMount(){
文件名称=
(this.props.title?this.props.title+'-':'')+“网站名称”;
}
render(){
const{component,…props}=this.props;
const PageComponent=组件;
返回;
}
}