我正在寻找一种在 React-Router v4+ 更改位置时修改页面标题的方法。我曾经在 Redux 中监听位置更改操作,并根据 metaData
对象检查该路由。
使用 React-Router v4+ 时,没有固定的路由列表。事实上,站点周围的各种组件都可以使用具有相同路径字符串的 Route
。这意味着我使用的旧方法将不再有效。
有没有一种方法可以通过在某些主要路线更改时调用操作来更新页面标题,或者是否有更好的方法来更新站点的元数据?
最佳答案
<Route />
组件有render属性(property)。因此,您可以在位置更改时通过声明路线来修改页面标题:
<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;
然后使用Page
在 render
路线的 Prop :
<Route
path="/about"
render={(props) => (
<Page title="Index">
<Index {...props} />
</Page>
)}
/>
<Route
path="/profile"
render={(props) => (
<Page title="Profile">
<Profile {...props} />
</Page>
)}
/>
关于reactjs - 有没有办法用React-Router v4+修改页面标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52447828/