原文: 从零开始React服务器渲染
gitclonegit@github.com:MrCuriosity/react-server-render-demo.gitnpminstallwebpack--watchnodeserver/index.jsthen visit 127.0.0.1:8082
同一个模块里
require和export可以混用,而import和module.exports则可以,详见 Cannot assign to read only property 'exports' of object '#< Object >' (mix require and export) #4039.箭头函数作用域问题, app/App.js
varApp=React.createClass({getInitialState: ()=>{return{count: this.props.initialCount}},_increment: ()=>{this.setState({count: this.state.count+1})},render: ()=>{console.log(this)//undefinedreturn(<div><span>the count is: </span><spanonClick={this._increment}>{this.state.count}</span></div>)}})varApp=React.createClass({getInitialState(){return{count: this.props.initialCount}},_increment(){this.setState({count: this.state.count+1})},render(){console.log(this)//a App class instanceconsole.log(this.constructor===App)// truereturn(<div><span>the count is: </span><spanonClick={this._increment}>{this.state.count}</span></div>)}})代码块1构造函数App中用了arrow function写法。构造函数的this指向他的实例, 而箭头函数的this指向上一级作用域(outer scope), 这里的this是undefined, 表明这里的this遵从的是箭头函数的规则, 并且, MDN - Arrow functions也有说明,不要将构造函数和箭头函数混用,否则报错。
- server/page.js 这里
var React = require('react'),而没有显氏的调用,但如果没有这一句,会报:React is not defined, 查看page.generator.js可以看到,
constcontent=ReactDOMServer.renderToString(<AppinitialCount={props.initialCount}/>)变成了
constcontent=ReactDOMServer.renderToString(React.createElement(App,{initialCount: props.initialCount}));.jsx作为React.createElement的语法糖最终调用的还是会调用React,所以必须有const React = require('react')
react server render作为前后端同构、直出的基础,同一个模板(app/App.js)可以运行在客户端与服务器端,首页数据和模块比较多的情况下后端渲染能提升不少性能,加快首屏渲染时间与首次可交互时间.不过个人觉得小项目就没必要,怎么简单怎么来,毕竟现在的前端已经很过度架构和过度工具了