使用同构应用程序设置应用程序初始状态的一般做法是什么?如果没有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架构中有操作和存储时,这一原则将如何工作?在我的组件中,我可以做到:
getInitialState: function() {
return AppStore.getAppState();
}
但是现在我如何从服务器设置AppStore中的初始状态呢?如果我在没有传递属性的情况下使用React.renderToString
,它将调用AppStore.getAppState()
,而AppStore.getAppState()
中不会有任何内容,因为我仍然不明白如何在服务器上的存储中设置状态?
更新日期:2015年2月5日
我仍在寻找一个干净的解决方案,不涉及使用第三方Flux实现,比如Fluxible, Fluxxor, Reflux.
更新日期:2016年8月19日
使用Redux.