[英]Dynamic page title with ReactJS
I want to make a Dynamic page title on ReactJS.我想在 ReactJS 上制作一个动态页面标题。 I try a lot of things, but didn't succeed.
我尝试了很多东西,但没有成功。 I make an array with data:
我用数据制作了一个数组:
let pageTitles = [
{key:"/Home", title:"Welcome Home"},
{key:"/SecondPage", title:"Shop"},
{key:"/ThirdPage", title:"ContactUs"},
];
In html is only <title></title>
, I use let pathname = window.location.pathname;
在 html 只有
<title></title>
,我使用let pathname = window.location.pathname;
If it return "/Home" or "/ThirdPage" to set a new title dynamically.如果它返回“/Home”或“/ThirdPage”来动态设置新标题。 I've tried something like that:
我试过这样的事情:
for (var i = 0, len = pageTitles.length; i < len; i++) {
if (pageTitles[i].key === pathname) {
var hhh = pageTitles[i].text;
}
}
document.title = hhh
But obviously didn't work.但显然没有奏效。 I'm sorry if there is a topic like that, but I didn't found it.I have a restriction to install modules.
如果有这样的话题,我很抱歉,但我没有找到它。我对安装模块有限制。
If you need to avoid installing modules, you could do this as helper file, then just import it in module you need and call in componentDidMount
如果您需要避免安装模块,您可以将其作为帮助文件执行,然后只需将其导入您需要的模块并调用
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>;
}
}
You could also just call directly document.title = 'My new title'
anywhere, but if you extract it as function you have the option to have default one and just provide override when you want to.您也可以在任何地方直接调用
document.title = 'My new title'
,但如果您将其提取为 function 您可以选择使用默认值并在需要时提供覆盖。
Edit: upon inspecting your code, if you change hhh = pageTitles[i].text;
编辑:在检查您的代码时,如果您更改
hhh = pageTitles[i].text;
to hhh = pageTitles[i].title;
到
hhh = pageTitles[i].title;
it will work.它会起作用的。 Would be nice to declare the
var
outside of the loop.在循环之外声明
var
会很好。 Also would be nice to have default value.拥有默认值也很好。
you have to use a react-helmet to solve this problem.你必须使用 react-helmet 来解决这个问题。 react-helmet is very useful for SEO for React projects.
react-helmet 对于 React 项目的 SEO 非常有用。
this is the link of the react-helmet这是反应头盔的链接
I hope this answer help you.我希望这个答案对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.