在客户端和服务器端设置文档标题

Oli*_*rdy 8 reactjs

我想知道如何使用ReactJS设置每个页面的标题.而且,我使用react-router-component,我希望使用相同的技术,通过使用React.renderComponentToString为服务器端的每个页面设置标题.

我当前的根组件:

module.exports = App = React.createClass
  getInitialState: ->
    return title: 'My title'

  render: ->
    <html lang="fr">
      <head>
        <link rel="stylesheet" href="/assets/css/main.css" />
        <script src="/assets/js/bundle.js"></script>
        <title>{@state.title}</title>
      </head>
      <body>
        <div id="body-content">
          <div id="main-container">
            <Content path={@props.path} />
          </div>
        </div>
      </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我的内容组件:

Content = React.createClass
  render: ->
    <Locations id="main" className="App" path={@props.path}>
      <Location path="/" handler={MainPage} />
      <Location path="/users/:username" handler={UserPage} />
    </Locations>
Run Code Online (Sandbox Code Playgroud)

joa*_*eng 1

要将标题传递到App组件服务器端,您必须以与传递path,即 asprops和 not相同的方式传递它state

所以首先你需要改变:

<title>{@state.title}</title>
Run Code Online (Sandbox Code Playgroud)

到:

<title>{@props.title}</title>
Run Code Online (Sandbox Code Playgroud)

然后在后端在App实例化组件时将所需的标题传递给组件,如下所示:

var url = require('url');
var ReactAsync = require('react-async');

var App = require('./path/to/your/root-component.jsx');

// app = your express app:
app.get('*', function (req, res) {
  var path = url.parse(req.url).pathname;
  var title = getTitleFromPath(path); // Made up function to get title from a path..
  ReactAsync.renderComponentToStringWithAsyncState(
    App({path: path, title: title}),
    function (err, markup) {
      if (err) return res.send(500, err);
      res.send('<!DOCTYPE html>\n' + markup);
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

至于设置标题客户端,我认为您设置的解决方案document.title可能是最好的选择。

更新

我现在已经测试了上面的内容,并且标题设置正确,但是 React 为服务器生成的组件和客户端生成的组件获取了不同的校验和,这不好:

Uncaught Error: Invariant Violation: You're trying to render a component to the document using server rendering but the checksum was invalid
Run Code Online (Sandbox Code Playgroud)

所以实际上你不应该使用这个解决方案!

还得再玩一会儿……