在渲染之前将数据从服务器传递到客户端的最常见方法是将数据嵌入到 React 正在渲染的页面上的全局 JavaScript 变量中。
因此,例如,在中间件中,您实际上正在渲染一些模板,其中包含您的 React 应用程序中的 <script> 标签,您可以添加信息并在模板上抓取它:
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>
但是显然react-engine 已经提供了自己的方式来在客户端发送数据:
组件渲染数据
输入组件进行渲染的实际数据是 express 生成的 renderOptions 对象。
https://github.com/paypal/react-engine#data-for-component-rendering
正如您在this example 中看到的那样,movies json 只是被传递到渲染中:
app.get('*', function(req, res) {
res.render(req.url, {
movies: require('./movies.json')
});
});
然后,借助框架的魔力,可能在this line 上,为您的组件提供信息,然后List 使用来自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 中可用。
对于非常好奇的人:
确实,正如我们在 this line onwards 上看到的那样,引擎合并了 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));