在渲染之前将数据从服务器传递到客户端的最常见方法是将其嵌入到React 正在渲染的页面上的全局 JavaScript 变量中。
因此,例如,在您实际渲染一些模板的中间件中,其中包含您<script>
的 React 应用程序的标签,您可以添加信息并在模板上抓取它:
var config = require('../config-from-somewhere');
app.get('/', function (req, res) {
res.render('index', {config: JSON.stringify(config)});
});
还有一个示例胡子模板:
<html>
<body>
<script>
window.CONFIG = JSON.parse({{{config}}});
</script>
<script src="my-react-app.js"/>
</body>
</html>
HOWEVER显然react-engine
已经提供了自己的方式在客户端发送数据:
组件渲染数据
输入组件进行渲染的实际数据是 express 生成的 renderOptions 对象。
https://github.com/paypal/react-engine#data-for-component-rendering
正如你在这个例子中看到的那样,movies
json 只是被传递给 render:
app.get('*', function(req, res) {
res.render(req.url, {
movies: require('./movies.json')
});
});
然后,借助框架的魔力,可能在这一行中,为您的组件提供了信息,然后列表从props.movies
.
module.exports = React.createClass({
displayName: 'List',
render: function render() {
return (
<div id='list'>
<h1>Movies</h1>
<h6>Click on a movie to see the details</h6>
<ul>
{this.props.movies.map(function(movie) {
return (
<li key={movie.id}>
<Router.Link to={'/movie/' + movie.id}>
<img src={movie.image} alt={movie.title} />
</Router.Link>
</li>
);
})}
</ul>
</div>
);
}
});
因此,基本上将您添加config
到您的渲染调用中,它应该在您的组件的props
.
对于非常好奇的人:
事实上,正如我们在这一行开始看到的那样,引擎合并renderOptions
并res.locals
最终将其传递给 React。
// create the data object that will be fed into the React render method.
// Data is a mash of the express' `render options` and `res.locals`
// and meta info about `react-engine`
var data = merge({
__meta: {
// get just the relative path for view file name
view: null,
markupId: Config.client.markupId
}
}, omit(options, createOptions.renderOptionsKeysToFilter));
和:
return React.createElement(Component, merge({}, data, routerProps));