Skip to content

zenjava/react-server-render-demo

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

###React-Server-Render Demo

原文: 从零开始React服务器渲染

git clone git@github.com:MrCuriosity/react-server-render-demo.git
npm install
webpack --watch
node server/index.js

then visit 127.0.0.1:8082

敲demo中遇到的坑:

var App = React.createClass({

	getInitialState: ()=> {
		return { count: this.props.initialCount }
	},
	
	_increment: ()=> { this.setState({ count: this.state.count + 1 })},

	render: ()=> {
	    console.log(this) //undefined
		return (
			<div>
				<span>the count is: </span>
				<span onClick={ this._increment }>{ this.state.count }</span>
			</div>
		)
	}
})
    var App = React.createClass({

	getInitialState() {
		return { count: this.props.initialCount }
	},
	
	_increment() { this.setState({ count: this.state.count + 1 })},

	render() {
	    console.log(this) //a App class instance
		console.log(this.constructor === App) // true
		return (
			<div>
				<span>the count is: </span>
				<span onClick={ this._increment }>{ this.state.count }</span>
			</div>
		)
	}
})

代码块1构造函数App中用了arrow function写法。构造函数的this指向他的实例, 而箭头函数的this指向上一级作用域(outer scope), 这里的thisundefined, 表明这里的this遵从的是箭头函数的规则, 并且, MDN - Arrow functions也有说明,不要将构造函数和箭头函数混用,否则报错。

  • server/page.js 这里var React = require('react'),而没有显氏的调用,但如果没有这一句,会报:React is not defined, 查看page.generator.js可以看到,
const content = ReactDOMServer.renderToString(<App initialCount={ props.initialCount } />)

变成了

const content = ReactDOMServer.renderToString(React.createElement(App, { initialCount: props.initialCount }));

.jsx作为React.createElement的语法糖最终调用的还是会调用React,所以必须有const React = require('react')


react server render 作为前后端同构、直出的基础,同一个模板(app/App.js)可以运行在客户端与服务器端,首页数据和模块比较多的情况下后端渲染能提升不少性能,加快首屏渲染时间与首次可交互时间.不过个人觉得小项目就没必要,怎么简单怎么来,毕竟现在的前端已经很过度架构和过度工具了

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%