the*_*ill 6 javascript flux node.js reactjs isomorphic-javascript
关于同构通量应用程序中存储数据填充的问题.(我正在使用react,alt,iso和node,但理论适用于其他示例)
我有一个需要从api获取数据的flux'store '(http://alt.js.org/docs/stores/):
getState() {
return {
data : makeHttpRequest(url)
}
}
Run Code Online (Sandbox Code Playgroud)
当用户浏览SPA时,将通过http请求加载更多数据.
我希望这个应用程序是同构的,以便我可以渲染应用程序完整的HTML,包括最新的数据服务器端,并将其返回给用户,以便快速初始页面加载.
react.renderToString()让我将应用程序渲染为html,我可以使用alt和iso播种数据,如:
storeData = { "MyStore" : {"key" : "value"}}; // set data for store
alt.bootstrap(JSON.stringify(storeData || {})); // seed store with data
var content = React.renderToString(React.createElement(myApp)); // render react app to html
Run Code Online (Sandbox Code Playgroud)
问题是我在运行js服务器端时会看到错误,因为商店想要发出一个它无法做的http请求(因为xmlhttprequest不存在于节点中)
什么是解决这个问题的最佳方法?
我能想到的唯一解决方案是从商店包装httprequest:
var ExecutionEnvironment = require('react/lib/ExecutionEnvironment');
...
if (ExecutionEnvironment.canUseDOM) {
// make http request
} else {
// do nothing
}
Run Code Online (Sandbox Code Playgroud)
有更好的想法吗?提前致谢.
如果您在服务器端运行,我建议直接连接到您的 Ajax 库或 XMLHttpRequest。只需使用直接从数据库或应用程序提供数据的代码填充它即可。
一个简单的例子:
var noop= function(){}
window.XMLHttpRequest= function(){
console.log("xhr created", arguments);
return {
open: function(method, url){
console.log("xhr open", method, url);
// asynchronously respond
setTimeout(function(){
// pull this data from your database/application
this.responseText= JSON.stringify({
foo: "bar"
});
this.status= 200;
this.statusText= "Marvellous";
if(this.onload){
this.onload();
}
// other libs may implement onreadystatechange
}.bind(this), 1)
},
// receive data here
send: function(data){
console.log("xhr send", data);
},
close: noop,
abort: noop,
setRequestHeader: noop,
overrideMimeType: noop,
getAllResponseHeaders: noop,
getResponseHeader: noop,
};
}
$.ajax({
method: "GET",
url: "foo/bar",
dataType: "json",
success: function(data){
console.log("ajax complete", data);
},
error: function(){
console.log("something failed", arguments);
}
});
Run Code Online (Sandbox Code Playgroud)
我在最后 5 分钟内主要使用XMLHTTPRequest mdn 页面完成了这个工作
但是,如果您使用的任何内容不直接基于 XMLHttpRequest 或显式节点感知(如 superagent),您可能需要对库函数本身进行填充。
在此代码片段上要做的其他工作是实现错误和不同的内容类型。
| 归档时间: |
|
| 查看次数: |
564 次 |
| 最近记录: |