有没有办法用 React-Router v4 修改页面标题?

新手上路,请多包涵

我正在寻找一种在 React-Router v4+ 更改位置时修改页面标题的方法。我曾经在 Redux 中监听位置更改操作,并根据 metaData 对象检查该路由。

使用 React-Router v4+ 时,没有固定的路由列表。事实上,站点周围的各种组件都可以使用 Route 具有相同的路径字符串。这意味着我使用的旧方法将不再有效。

有没有一种方法可以在某些主要路线发生变化时通过调用操作来更新页面标题,或者是否有更好的方法来更新站点的元数据?

原文由 Kevin Ghadyani 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 962
2 个回答

在您的 componentDidMount() 方法中为每个页面执行此操作

componentDidMount() {
  document.title = 'Your page title here';
}

这将更改您的页面标题,为每条路线执行上述操作。

此外,如果它不仅仅是标题部分,请检查 react-helmet 它是一个非常简洁的库,并且还处理了一些不错的边缘情况。

原文由 Adeel Imran 发布,翻译遵循 CC BY-SA 4.0 许可协议

<Route /> 组件具有 渲染 属性。因此,您可以通过这样声明您的路线来在位置更改时修改页面标题:

 <Route
  exact
  path="/"
  render={props => (
    <Page {...props} component={Index} title="Index Page" />
  )}
/>

<Route
  path="/about"
  render={props => (
    <Page {...props} component={About} title="About Page" />
  )}
/>

Page 组件中你可以设置路由标题:

 import React from "react"

/*
 * Component which serves the purpose of a "root route component".
 */
class Page extends React.Component {
  /**
   * Here, we define a react lifecycle method that gets executed each time
   * our component is mounted to the DOM, which is exactly what we want in this case
   */
  componentDidMount() {
    document.title = this.props.title
  }

  /**
   * Here, we use a component prop to render
   * a component, as specified in route configuration
   */
  render() {
    const PageComponent = this.props.component

    return (
      <PageComponent />
    )
  }
}

export default Page

2019 年 8 月 1 日更新。这仅适用于 react-router >= 4.x。感谢@supremebeing7

使用 React Hooks 更新答案

您可以使用下面的组件指定任何路由的标题,该组件是使用 useEffect 构建的。

 import { useEffect } from "react";

const Page = (props) => {
  useEffect(() => {
    document.title = props.title || "";
  }, [props.title]);
  return props.children;
};

export default Page;

然后在路由的 render 道具中使用 Page

 <Route
  path="/about"
  render={(props) => (
    <Page title="Index">
      <Index {...props} />
    </Page>
  )}
/>

<Route
  path="/profile"
  render={(props) => (
    <Page title="Profile">
      <Profile {...props} />
    </Page>
  )}
/>

原文由 phen0menon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进