使用同构应用程序设置应用程序初始状态的一般做法是什么?如果没有 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()
其中没有任何内容,因为我仍然不明白如何在服务器上的商店中设置状态?
2015 年 2 月 5 日更新
我仍在寻找一个干净的解决方案,它不涉及使用第三方 Flux 实现,如Fluxible、Fluxxor、Reflux。
2016 年 8 月 19 日更新
使用Redux。