使用 ReactJS 的动态页面标题



我想在ReactJS上做一个动态页面标题。我尝试了很多东西,但没有成功。我用数据做一个数组:

let pageTitles = [
{key:"/Home", title:"Welcome Home"},
{key:"/SecondPage", title:"Shop"},
{key:"/ThirdPage", title:"ContactUs"},
];

在html中只<title></title>,我使用let pathname = window.location.pathname;如果它返回"/Home"或"/ThirdPage"来动态设置新标题。 我试过这样的事情:

for (var i = 0, len = pageTitles.length; i < len; i++) {
if (pageTitles[i].key === pathname) {
var hhh = pageTitles[i].text;
}
}
document.title = hhh

但显然没有用。如果有这样的话题,我很抱歉,但我没有找到它。我有安装模块的限制。

如果您需要避免安装模块,则可以将其作为辅助文件进行,然后将其导入所需的模块并调用componentDidMount

export function seo(data = {}) {
data.title = data.title || 'Default title';
data.metaDescription = data.metaDescription || 'Default description';
document.title = data.title;
document.querySelector('meta[name="description"]').setAttribute('content', data.metaDescription);
}
import React from 'react';
import {seo} from '../helpers/seo';
export default class SomeClass extends Component {
constructor(props) {
super(props);
};
componentDidMount() {
seo({
title: 'This is my title only shown on this page',
metaDescription: 'With some meta description'
});
}
render() {
return <h1>Hello World</h1>;
}
}

您也可以直接document.title = 'My new title'任何地方调用,但是如果您将其提取为函数,则可以选择默认函数,并在需要时提供覆盖。

编辑:检查代码后,如果将hhh = pageTitles[i].text;更改为hhh = pageTitles[i].title;它将起作用。最好在循环之外声明var。有默认值也很好。

最新更新