English 中文(简体)
是否有办法修改“React-Router诉4+”的页标题?
原标题:Is there a way to modify the page title with React-Router v4+?

I m 寻求在React-Router v4+变化地点修改页标题的方法。 我曾听说在红色地区采取地点变更行动,并检查该路线与<代码>metaData的物体。

在使用React-Router诉4+时,没有固定路线清单。 事实上,网站周围的各个组成部分可使用<代码>Route,并使用相同的路径图。 这意味着旧的方法,我使用的是打工。

Is there a way I can update the page title by calling actions when certain major routes are changed or is there a better a better method to update the site s metadata?

最佳回答

www.un.org/Depts/DGACM/index_spanish.htm 我询问了问题“如何正确确定所有权” 官方“真实路线”背书answered “这只是路人所为。 You re look for a Library such asactive-helmet.

If you want to change title in react router tutorial, you just need to

npm install react-helmet

之后再到您的反应路线上(例如contact.jsx),并添加这种代码

import { Helmet } from "react-helmet";

export default function Contact() {
  const { contact } = useLoaderData();
  return (
    <div id="contact">

      <Helmet>
        <title>{ contact.first?? Новый контакт  }</title>
      </Helmet>

And it works correctly in march 2023.

问题回答

。 因此,在地点发生变化时,你可以更改网页名称,宣布:

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

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

In Page component you can set the route title:

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

Update 1 Aug 2019. This only works with react-router >= 4.x. Thanks to @supremebeing7

www.un.org/Depts/DGACM/index_spanish.htm https://reactjs.org/docs/hooks-effect.html React Hooks:

You can specify the title of any route using the component below, which is built by using useEffect.

import { useEffect } from "react";

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

export default Page;

And then use Page in the render prop of a route:

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

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

在您的<代码>componentDidMount()中,每一页都采用了这一方法。

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

This will change your page title, do the above mentioned for every route.

Also if it is more then just the title part, check react-helmet It is a very neat library for this, and handles some nice edge cases as well.

https://stackoverflow.com/a/54112771”

import React, { useEffect } from  react ;
import { Route } from  react-router-dom ;
import PropTypes from  prop-types ;

export const Page = ({ title, ...rest }) => {
  useEffect(() => {
    document.title = title;
  }, [title]);
  return <Route {...rest} />;
};

这将消除下述间接费用代码:

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

// improvement:
  <Page
    exact
    path="/"
    component={Index}
    title="Index Page"
  />

http://reactjs.org/docs/hooks-custom.html hook :

import { useEffect } from  react ;

/** Hook for changing title */
export const useTitle = title => {
  useEffect(() => {
    const oldTitle = document.title;
    title && (document.title = title);
    // following line is optional, but will reset title when component unmounts
    return () => document.title = oldTitle;
  }, [title]);
};

我在Thierry Prosts解决方案上建立了一条轨道,最后如下:

www.un.org/Depts/DGACM/index_french.htm 2008年1月: 我现在更新了我的内容,以便也能够描述:

www.un.org/Depts/DGACM/index_french.htm 2021年8月: 我在《字典》中增加了我的私人路线。

import React, { FunctionComponent, useEffect } from  react ;
import { Route, RouteProps } from  react-router-dom ;

interface IPageProps extends RouteProps {
  title: string;
}

const Page: FunctionComponent<IPageProps> = props => {
  useEffect(() => {
    document.title = "Website name | " + props.title;
  });

  const { title, ...rest } = props;
  return <Route {...rest} />;
};

export default Page;

UPDATE: My Page.jsx component is now a functional component and with useEffect hook:

import React, { useEffect } from  react ;
import { Route } from  react-router-dom ;

const Page = (props) => {
  useEffect(() => {    
    document.title = "Website name | " + props.title;
  });

  const { title, ...rest } = props;
  return <Route {...rest} />;
}

export default Page;

下面你可以找到我的初步解决办法:

// Page.jsx
import React from  react ;
import { Route } from  react-router-dom ;

class Page extends Route {
  componentDidMount() {
    document.title = "Website name | " + this.props.title;
  }

  componentDidUpdate() {      
      document.title = "Website name | " + this.props.title;
  }

  render() {
    const { title, ...rest } = this.props;
    return <Route {...rest} />;
  }
}

export default Page;

我的路线实施就是这样:

// App.js / Index.js
<Router>
    <App>
      <Switch>
         <Page path="/" component={Index} title="Index" />
         <PrivateRoute path="/secure" component={SecurePage} title="Secure" />
      </Switch>
    </App>    
  </Router>

Private route setup:

// PrivateRoute
function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Page
      {...rest}
      render={props =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}

2. 私人途径:

export const PrivateRoute = ({ Component, ...rest }: IRouteProps): JSX.Element => {
  return (
    <Page
      {...rest}
      render={(props) =>
        userIsAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: Paths.login,
              state: { from: props.location },
            }}
          />
        )
      }
    />
  );
};

这使我能够更新有新头衔的公共领域,并更新私人领域。

在赫尔曼特的帮助下:

import React from  react 
import Helmet from  react-helmet 
import { Route, BrowserRouter, Switch } from  react-router-dom 

function RouteWithTitle({ title, ...props }) {
  return (
    <>
      <Helmet>
        <title>{title}</title>
      </Helmet>
      <Route {...props} />
    </>
  )
}

export default function Routing() {
  return (
    <BrowserRouter>
      <Switch>
        <RouteWithTitle title="Hello world" exact={true} path="/" component={Home} />
      </Switch>
    </BrowserRouter>
  )
}

I am answering this because I feel you could go an extra step to avoid repetitions within your components and you could just get the title updated from one place (the router s module).

I usually declare my routes as an array but you could change your implementation depending on your style. so basically something like this ==>

import {useLocation} from "react-router-dom";
const allRoutes = [
  {
        path: "/talkers",
        component: <Talkers />,
        type: "welcome",
        exact: true,
    },
    {
        path: "/signup",
        component: <SignupPage />,
        type: "onboarding",
        exact: true,
    },
  ]

const appRouter = () => {
    const theLocation = useLocation();
    const currentLocation = theLocation.pathname.split("/")[1];
    React.useEffect(() => {
        document.title = `<Website Name> | 
        ${currentLocation[0].toUpperCase()}${currentLocation.slice(1,)}`
    }, [currentLocation])

   return (
     <Switch>
      {allRoutes.map((route, index) => 
        <Route key={route.key} path={route.path} exact={route.exact} />}
    </Switch>

   )

}

Another approach would be declaring the title already in each of the allRoutes object and having something like @Denis Skiba s solution here.

也可使用<代码>render。 方法

const routes = [
 {
   path: "/main",
   component: MainPage,
   title: "Main Page",
   exact: true
 },
 {
   path: "/about",
   component: AboutPage,
   title: "About Page"
 },
 {
   path: "/titlessPage",
   component: TitlessPage
 }
];

const Routes = props => {
 return routes.map((route, idx) => {
   const { path, exact, component, title } = route;
   return (
     <Route
       path={path}
       exact={exact}
       render={() => {
         document.title = title ? title : "Unknown title";
         console.log(document.title);
         return route.component;
       }}
     />
   );
 });
};

codesand Box (明显导致新窗口见标题)

如果你只是想表明该构成部分的标题,那么以下守则的例子也应发挥作用:

useEffect(() =>
{
    document.title = "My page title";
}, []);

I have a short and simple solution using react hook with or without react router.

我刚刚创建了一个名为“文件”的文件:

import React, { useEffect } from  react ;

const useDocumentTitle = (title: string, default_title: string | undefined 
=  My default title ) => {
  useEffect(() => {
    document.title = title +   |   + default_title;
    return () => {
      document.title = default_title;
    };
  }, []);
};

export default useDocumentTitle;

如果我想根据参数的变化动态地改变文件标题,我将在<代码>依附阵列<>>上添加<代码><<>>>> > > > > 不适用

useEffect(() => {
    document.title = title +   |   + default_title;
    return () => {
        document.title = default_title;
    };
}, [title]);

In my components, I just add :

useDocumentTitle( Customer )

如果我想将标题改为不同的缺省标题,则留下页:

useDocumentTitle( Customer ,  My Company Info )




相关问题
Page title structure: SEO and accessibility

I am choosing a page title structure for my website and am unsure what to choose in terms of accessibility and SEO. Is there a benefit to putting site title after the page title because of the unique ...

UpdatePanel seems to re-encode characters in the page title?

I have pages with special characters in the title for proper typography, for example it says Exchange ‘07 Groups" with a proper apostrophe, not a single quote. The HTML entity for the apostrophe ...

custom pages give 404 error title in Wordpress

I m running a site powered by WordPress with extra pages... To integrate these pages with the WordPress theme I use this code: <?php $blog_longd= Title ; // page title define( WP_USE_THEMES , ...

Prepend to the title tag using jQuery?

I want to have my title tag look like this: My Website - Name of Page I want to prepend the My Website - part so that I don t have to type it on every new page I make. So the title tag that I ...

How to use Eval in codebehind to set Page.Title

I have a SQLDataSource that is bound to a ListView control but I want to place parts of the bound record into the HTML TITLE attribute. Here is my codebehind file that I want to change so it can use ...

Title on Master Page on ASP.Net MVC

To manage page title on page s,I have a master page where i am taking ContentPlaceHolder. <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /> </title> and on ...

Setting the Page-Title in .Net using C# from a Class

Question, How do i set the title of a page from a class. Is it even possible? I can and have set the page title from a page itself and a usercontrol. Can I, How Do I do this via a class using C# ....

热门标签