react-helmet在服务器端输出空字符串

时间:2017-08-22 16:35:23

标签: reactjs react-router serverside-rendering react-helmet

我正在使用react-helmet,并且在客户端上,在检查窗口中一切都很好并且标签正确输出。但是,当我在制作中启动时,SSR中的标签没有显示在源代码中,而我根本没有错误。

我尝试记录'字符串化'标题标签也得到了:

<title data-react-helmet="true"></title>

以下是一些代码:

这是我设置标签的页面组件之一,3页组件都设置与此相同。 (我已经简化了组件渲染功能和数据对象,因为它们非常大,我确信这些都没有错。)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';

// Components
import WorkGrid from 'universal/components/Grid';
import Wrapper from 'universal/components/Wrapper';
import Container from 'universal/components/Container';
import Hero from 'universal/components/Hero';
import PageWrapper from 'universal/components/PageWrapper';
import GridHeader from 'universal/components/GridHeader';

const data = {};

class Work extends PageComponent {

  render () {
    return (
      <PageWrapper ref="root">
        <Helmet>
          <title>Work</title>
          <meta name="description" content="Work Description" />
        </Helmet>
        <h1>Work Page</h1>
      </PageWrapper>
    );
  }
}

export default connect(state => ({
  theme: state.ui.theme
}), { changeTheme }, null, { withRef: true })(Work);

这是一些服务器代码,特别是在SSR发生故障的情况下,我正在调用Helmet.renderStatic();

    // Node Modules
import fs from 'fs';
import {basename, join} from 'path';

// Libraries
import React from 'react';
import {StaticRouter} from 'react-router';
import {renderToString} from 'react-dom/server';

// styled-components
import { ServerStyleSheet, ThemeProvider } from 'styled-components';
import { theme } from '../universal/constants';

// Redux
// import {push} from 'react-router-redux';
import createStore from 'data/redux/createStore.js';
import createHistory from 'history/createMemoryHistory';
import { Provider } from 'react-redux';

// Third Party Scripts
import * as thirdPartyScripts from './thirdPartyScripts.js';

// Helmet
import {Helmet} from 'react-helmet';

function renderApp(url, res, store, assets) {
  const PROD = process.env.NODE_ENV === 'production';
  const context = {};

  const {
    manifest,
    app,
    vendor
  } = assets || {};

  let state = store.getState();

  const stylesheet = new ServerStyleSheet();

  const initialState = `window.__INITIAL_STATE__ = ${JSON.stringify(state)}`;
  const Layout =  PROD ? require( '../../build/prerender.js') : () => {};

  const root = PROD && renderToString(
    stylesheet.collectStyles(
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <StaticRouter location={url} context={context}>
            <Layout />
          </StaticRouter>
        </ThemeProvider>
      </Provider>
    )
  );

  const styleTags = stylesheet.getStyleTags();

  const seo = Helmet.renderStatic();

  console.log(seo.title.toString());

  const html = `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        ${seo.title.toString()}
        ${seo.meta.toString()}
        ${seo.link.toString()}

        <link rel="shortcut icon" href="/favicon.ico">
        <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
        <link rel="apple-touch-icon" href="/favicon-57.png">
        <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
        <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
        <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
        <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
        <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
        <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
        <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">
        <meta name="msapplication-TileColor" content="#FFFFFF">
        <meta name="msapplication-TileImage" content="/favicon-144.png">
        <meta name="msapplication-config" content="/browserconfig.xml">

        ${ styleTags }

        ${PROD ? '<link rel="stylesheet" href="/static/prerender.css" type="text/css" />' : ''}

        <link href="${thirdPartyScripts.googleFont}" rel="stylesheet" type="text/css">

        <script>${thirdPartyScripts.googleAnalytics}</script>
    </head>

    <body>
      <script>${initialState}</script>
      ${PROD ? `<div id="root">${root}</div>` : '<div id="root"></div>'}

      ${PROD ? `<script>${manifest.text}</script>` : ''}

      <script>${thirdPartyScripts.facebookPixel}</script>

      <script async src="${thirdPartyScripts.googleAnalyticsSrc}"></script>
      ${PROD ? `<script src="${vendor.js}"></script>` : ''}
      <script src="${PROD ? app.js : './static/app.js'}"></script>
    </body>
    </html>`;

  res.send(html);
}

此外,我正在使用React Router v4,如果有任何帮助的话。

1 个答案:

答案 0 :(得分:3)

我在另一周找到了解决方案,并认为我也可以更新这个,以便它可以帮助其他人解决这个问题......

好消息是它非常简单!

无论如何,对我而言,我将客户端和服务器的webpack包分开了。因此,在外行人的术语中,它包括两次react-helmet,一次用于客户端,一次用于服务器,这意味着在客户端代码中保存元标记的所有状态都不存在于.rewind中( )在服务器上打电话。

只需将此添加到您的服务器webpack配置文件

即可

externals: ['react-helmet']