我在React项目中有我的 index.html 页面,如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Bucard | Digital Business Card</title>
<meta name="title" content="Bucard | Digital Business Card">
<meta name="description" content="Bucard - Description for bucard" />
<meta property="og:title" content="Bucard | Digital Business Card" />
<meta property="og:image" content="http://m.digital-card.co.il/zedka/152/images/icon.png" />
<meta property="og:description" content="Bucard - Description for bucard" />
<meta property="og:url" content="https://bucard.co.il/" />
</head>
<body>
<div id="root"></div>
</body>
</html>
还有我的 react-helmet 部分,该部分存在于组件中,其自身的路径位于url上:
<Helmet>
<title>{"Digital card of " + this.state.card.Name}</title>
<meta name="title" content={"Digital card of " + this.state.card.Name} />
<meta name="description" content="Description for the react-helmet section" />
<meta property="og:title" content={"Digital card of " + this.state.card.Name} />
<meta property="og:image" content="http://m.digital-card.co.il/friedman/249/images/icon.png" />
<meta property="og:description" content="Description for the react-helmet section" />
<meta property="og:url" content={"https://bucard.co.il/digitalCard/" + this.state.card.ShortID} />
</Helmet>
现在,这里的问题是唯一替换此处的标签是
我没有服务器端渲染,我有服务器端(node.js)和返回一些值的json的函数,这些值是我在react应用程序中渲染的。
我搜索了将近2个星期,但仍无法解决,这对我的项目非常重要。
试图将data-react-helmet=true
置于不同的情况,但仍然无法正常工作。
有人可以帮我解决这个问题吗?非常感谢:)
答案 0 :(得分:1)
我遇到了同样的问题。并如下解决。
在您的服务器文件(比如 server/index.js)中,添加 在 ReactDOMServer.renderToString 之后 consthelm = Helmet.renderStatic()。我的代码看起来像:
onCreated
并添加以下函数。这是为了更新带有头盔标签的 html 内容。
onRendered
这可能对你有帮助:)
答案 1 :(得分:0)
对于没有SSR(服务器端呈现)的SPA,从机器人的角度来看,您的head标签位于dist / public文件夹中的static index.html文件中。要添加将动态元素从head标签投放到bot的功能,您可以:
您可以阅读-https://github.com/nfl/react-helmet/issues/489
一种对我有用的方法:
将流量定向到节点服务器
运行一个节点服务器,该服务器返回index.html文件并传递头标记。
return res.render('index', {
headTags: ReactDOMServer.renderToStaticMarkup(tags),
})
在这里,标签是由元,标题等元素组成的数组。您可以在前端使用相同的代码来获取头盔的头部标签。
在index.html中,您可以使用车把读取从节点服务器传递来的head标签并在head部分中打印head标签。
<head>
{{{
headTags
}}}
...
</head>
并且要使用车把作为引擎,请将其添加到您的节点服务器
app.engine('html', handlebars.engine);