reactjs - react Helm 的目的是什么?

标签 reactjs react-helmet

我创建了一个服务器端 React 应用程序,它将返回 html,如下所示:

const html = renderToString(<App />);
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>A Cool Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
  <body>
    <div id="root">${html}</div>
    <script src="${ROOT}/client-bundle.js"></script>
  </body>
</html>

我读到很多人一直在使用 react-helmet 来管理 head 中的内容。我想知道使用它有什么好处,当我可以直接包含如上所示时。

最佳答案

react-helmet 的一个主要好处是当你在树中有多个组件时 <head>标签,你就有 <meta>具有相同属性/值的标签。

例如,如果您的索引页面组件上有:

const html = renderToString(<App />);
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="This is the index page description"> 
    <title>A Cool Index Page</title>
  </head>
</html>

但是在叶子页面组件上,您还有一个<head>包含元标记的标记:

<html>
  <head>
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>

请注意,我们的两个页面组件之间有两个具有相同属性值的元标记 name="description"在我们的树上。您可能认为这可能会导致重复,但是 react-helmet解决了这个问题。

如果有人最终到达叶子页面,react-helmet 会覆盖索引/站点级描述元标记并呈现较低级别的元标记,即专门用于叶子页面的元标记。

它还将包含视口(viewport)元标记,因为它不必被覆盖。

因为react-helmet ,在叶页上,<head>将显示如下:

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>

关于reactjs - react Helm 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690820/

相关文章:

javascript - 使用 Apollo 客户端在 nextJs 中传递授权 header 的最佳方式?引用错误 : localStorage is not defined

reactjs - 如何在ubuntu上为 digital ocean 设置防火墙?

reactjs - 在 React 中添加 favicon 到 <Helmet/>

javascript - gatsby-react-helmet 在 SSR 上生成空 &lt;title&gt;

javascript - 单元测试 react Helm 代码

node.js - 如何使用服务器端渲染设置 react-helmet?

javascript - 如何让 Service Worker 从 API 缓存数据并在需要时更新缓存

javascript - 更新数组中对象的值

reactjs - redux-form 获取输入的表单名称