【发布时间】:2016-03-21 17:31:02
【问题描述】:
当在服务器端渲染组件时,我已经能够将数据传递给响应组件,例如:
app.get('/', function (req, res, next) {
var reactHtml = ReactDOMServer.renderToString(component({data}));
res.render('index.jade', {reactOutput: reactHtml});
});
现在我把它改成了
server.js:
app.get('*', (req, res) => {
// match the routes to the url
match({ routes: routes, location: req.url }, (err, redirect, props) => {
props.data = {q:123};
const appHtml = ReactDOMServer.renderToString(routerContext(props));
res.render('index.jade', {reactOutput: appHtml});
})
});
路由器上下文
module.exports = React.createClass({
render: function(){return(<RouterContext {...this.props} />)}
});
和路线
module.exports = (
<Route path="/" component={App} {...this.props}>
<IndexRoute component={List}/>
<Route path="/about" component={About}/>
</Route>
);
App.jsx
var App = React.createClass({
render: function () {
console.log(this.props);
return (
<div id="app-root" className="container">
<Nav/>
<h1>{this.props.q}</h1>
{this.props.children}
<div className="Row">
<div className="footer col-lg-12"></div>
</div>
</div>
)
}
});
因此,例如,我想在我的 App 组件中从这一点 props.data = {q:123}; 获取数据,但是当我在 App 组件渲染方法中执行 console.log(this.data); 时,我有历史、位置等,但没有我的数据。无论如何要从 server.js 逻辑将数据 {q:123} 传递给组件(应用程序或列表或关于)道具?
(假设我们现在总是加载一些数据)
【问题讨论】:
标签: node.js express reactjs react-router isomorphic-javascript