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

时间:2021-03-16 09:05:37

标签: reactjs

我目前正在开发一个 React 项目,我想在我的页眉中显示当前页面标题。目前要做到这一点,我使用 props.location.pathname 和 switch-case 来获得所需的输出。

这看起来像下面。

    var currentPathname = this.props.location.pathname;

    switch (currentPathname) {
        case '/':
            return 'Home';
    }

路径的数量正在增加,我不想制作一个大的开关盒。所以我想知道,是否有更好的方法来根据路径设置(自定义)标题。我希望在 react-router 中有一些可用的东西,但我还没有找到这样的东西。

欢迎提供任何见解。

5 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

const path = this.props.location.pathname;
const title = path == '/' ? 'Home' : path == '/contact' ? 'customContactTitle' ...

你可以用它做一个钩子,比如“getTitle”,然后把它导入到你的页面中。

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

如果您使用 Next.js,您可以将路径及其相应的标题存储在数据库或 CMS 中,然后在构建时(使用 Next 的 getStaticProps)获取一次,如果这有助于维护。

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

答案 2 :(得分:0)

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

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

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

使用 <PageTitle path={this.props.location.pathname} /> 更新标题

答案 3 :(得分:0)

你可以通过维护一个 JSON 来实现

var titleForRoutes=[
{
route:"/",          //route 
title:"Home",       //title to show on header
component:HomePage  //React Component
},
{
route:"/Login",
title:"Login", 
component:LoginPage 
}
]

然后在路由中通过迭代该 Json 来声明路由,另一方面,您可以使用相同的 JSON 显示标题。

谢谢。

答案 4 :(得分:0)

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

<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} />;
  }
}