Reactjs - 服务器/客户端校验和不匹配错误

时间:2015-06-24 17:06:29

标签: reactjs

我想让React首先在服务器上渲染一个组件,然后用一个按钮更改客户端的状态。我已经按照几个教程说明了将组件放在服务器和客户端上的同一节点中,并使用相同的道具来执行此类操作。但是,我仍然收到无效的校验和错误消息,并且尝试单击该按钮会导致浏览器崩溃。我出错的任何想法?

组件:

var React = require('react')

module.exports = React.createClass({
getInitialState: function() {
    return { from: this.props.from }
},
handleClick: function(){
    this.setState({
        from: !this.state.clicked ? 'client!' : 'server!',
        clicked: !this.state.clicked
    });
},
render: function() {
    return (
        <div>
            <div>
                This is from the HelloWorld.jsx component's render function.
            </div>
            <div>
                Rendered from: {this.state.from}
            </div>
            <input type="button" value="Click Me" onClick={this.handleClick} />
        </div>
    )
}})

浏览器:

var React = require('react')
var HelloWorld = require('../Components/HelloWorld')

var helloElement = React.render(
    <HelloWorld from = "server!" />,
    document.getElementById("reactHelloContainer"))

服务器:

var React = require('react')
  , express = require('express')
  , HelloWorld = require('./Components/HelloWorld')
  , path = require('path')

var app = express()
app.use('/pages', express.static(path.join(__dirname, 'Pages')))

app.get('/', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'})
    var html = React.renderToString(
            <html>
                <head>
                    <title>Hello World</title>
                </head>
                <body>
                    <div id="reactHelloContainer">
                            <HelloWorld from="server!" />
                    </div>
                </body>
                <script src="/pages/index.js"></script>
            </html>)
    res.end(html)
})

我尝试在没有Javascript的情况下加载页面,服务器/客户端版本似乎相同,但这是消息:

  

警告:React尝试在容器中重用标记,但校验和无效。这通常意味着您正在使用服务器呈现,并且在服务器上生成的标记不是客户端所期望的。 React注入了新的标记以补偿哪些有效但你已经失去了服务器渲染的许多好处。相反,弄清楚为什么生成的标记在客户端或服务器上是不同的:

     

(client)eactid =“。1566xf5m134”&gt;      

(服务器)eactid =“。1566xf5m134.1.1.0”&gt;

1 个答案:

答案 0 :(得分:-2)

服务器getInitialState中设置的初始状态需要与浏览器中的初始状态匹配。实现此目的的一种方法是将初始道具传递给脚本标记中的浏览器,然后从脚本内容中获取道具。你可以使用模板传递道具。

浏览器HTML:

<div id='reactHelloContainer'></div>
<script id='hello-props'> {Your props in JSON here}   </script>

浏览器js:

var React = require('react');
var HelloWorld = require('../Components/HelloWorld');

component = React.createFactory(HelloWorld);
var props = JSON.parse(document.getElementById("hello-props").innerHTML);
React.render(component(props), document.getElementById('reactHelloContainer'));