在同构应用程序中,设置应用程序的初始状态的一般做法是什么?如果没有Flux,我会简单地使用类似以下的东西:
var props = { }; // initial state
var html = React.renderToString(MyComponent(props);
然后通过 express-handlebars 渲染该标记,再通过 {{{reactMarkup}}
显示。
在客户端为了设置初始状态,我会像这样做:
if (typeof window !== 'undefined') {
var props = JSON.parse(document.getElementById('props').innerHTML);
React.render(MyComponent(props), document.getElementById('reactMarkup'));
}
所以,实际上你在服务器和客户端都设置了状态两次,然而React会比较差异,在大多数情况下不会通过重新渲染来影响性能。
当使用Flux架构中的actions和stores时,这个原则如何运作呢?在我的组件内部我可以这样做:
getInitialState: function() {
return AppStore.getAppState();
}
现在我该如何从服务器上设置AppStore的初始状态呢? 如果我使用未传递属性的React.renderToString
,它将调用AppStore.getAppState()
,但其中不会有任何内容,因为我仍然不明白如何在服务器上设置存储中的状态。
更新于2015年2月5日
我仍在寻找一种不涉及使用第三方Flux实现(如Fluxible、Fluxxor、Reflux)的简洁解决方案。
更新于2016年8月19日
使用Redux。