Sah*_*bov 42 javascript flux express reactjs isomorphic-javascript
使用同构应用程序设置应用程序的初始状态的一般做法是什么?没有Flux我会简单地使用类似的东西:
var props = { }; // initial state
var html = React.renderToString(MyComponent(props);
Run Code Online (Sandbox Code Playgroud)
然后通过快速把手渲染该标记并显示通过{{{reactMarkup}}.
在客户端设置初始状态我会做这样的事情:
if (typeof window !== 'undefined') {
var props = JSON.parse(document.getElementById('props').innerHTML);
React.render(MyComponent(props), document.getElementById('reactMarkup'));
}
Run Code Online (Sandbox Code Playgroud)
所以基本上你是在服务器和客户端上设置状态两次,但是React会比较这些差异,在大多数情况下,它不会通过重新渲染来影响性能.
当您在Flux架构中拥有操作和存储时,此原则将如何工作?在我的组件里面我可以做到:
getInitialState: function() {
return AppStore.getAppState();
}
Run Code Online (Sandbox Code Playgroud)
但是现在我如何从服务器设置AppStore中的初始状态?如果我使用React.renderToString没有传递的属性,它将调用AppStore.getAppState()哪个不会有任何内容,因为我仍然不明白我将如何在服务器上的商店中设置状态?
我仍在寻找一种干净的解决方案,不涉及使用Fluxible,Fluxxor,Reflux等第三方Flux实施.
使用Redux.
Bri*_*and 14
看一下dispatchr和yahoo的相关库.
大多数flux实现在node.js中不起作用,因为它们使用单例存储,调度程序和操作,并且没有"我们已完成"的概念,这需要知道何时呈现到html并响应请求.
像fetchr和routr这样的Yahoo库通过使用非常纯粹的依赖注入形式来解决节点的这种限制(对于参数名称没有解析函数或类似的东西).
而是在services/todo.js中定义这样的api函数:
create: function (req, resource, params, body, config, callback) {
Run Code Online (Sandbox Code Playgroud)
在actions/createTodo.js中有类似的动作:
module.exports = function (context, payload, done) {
var todoStore = context.getStore(TodoStore);
...
context.dispatch('CREATE_TODO_START', newTodo);
...
context.service.create('todo', newTodo, {}, function (err, todo) {
Run Code Online (Sandbox Code Playgroud)
最后一行间接调用services/todo.js中的create函数.在这种情况下,间接可以表示:
这只是冰山一角.这是一组非常复杂的模块,它们协同工作以解决棘手的问题并提供可用的API.在现实世界的用例中,同构性本质上是复杂的.这就是为什么许多flux实现不支持服务器端渲染的原因.
您可能还想研究不使用flux.它对所有应用程序都没有意义,而且往往只是妨碍了.大多数情况下,如果有的话,你只需要它的几个部分.编程中没有银子弹!
如果您愿意使用alt.js,alt.bootstrap您可以使用and来实现它alt.flush(文档)
我使用 Node js 与 React 服务器端渲染和 alt.js 作为我的 Flux 实现。
它看起来是这样的:
var data = {}; // Get the data whatever you want and return it bootstrap ready.
// Reminder - renderToString is synchronised
var app = React.renderToString(
AppFactory(data)
);
// In this point the react rendering was finished so we can flush the data and reset the stores
alt.flush();
Run Code Online (Sandbox Code Playgroud)
在我的 app.jsx 中
/**
*
*/
componentWillMount: function () {
// This beauty here is that componentWillMount is run on the server and the client so this is all we need to do. No need for other third-party isomorphic frameworks
alt.bootstrap(
JSON.stringify(this.props, null, 3)
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8677 次 |
| 最近记录: |