【发布时间】:2016-01-04 00:04:31
【问题描述】:
我是反应和变化的新手,我很难弄清楚如何从服务器加载数据。我可以毫无问题地从本地文件加载相同的数据。
所以首先我有这个控制器视图 (controller-view.js),它将初始状态传递给视图 (view.js)
controller-view.js
var viewBill = React.createClass({
getInitialState: function(){
return {
bill: BillStore.getAllBill()
};
},
render: function(){
return (
<div>
<SubscriptionDetails subscription={this.state.bill.statement} />
</div>
);
}
});
module.exports = viewBill;
view.js
var subscriptionsList = React.createClass({
propTypes: {
subscription: React.PropTypes.array.isRequired
},
render: function(){
return (
<div >
<h1>Statement</h1>
From: {this.props.subscription.period.from} - To {this.props.subscription.period.to} <br />
Due: {this.props.subscription.due}<br />
Issued:{this.props.subscription.generated}
</div>
);
}
});
module.exports = subscriptionsList;
我有一个为我的应用加载 INITAL 数据的操作文件。所以这是不作为用户操作调用的数据,而是从控制器视图中的getInitialState调用
InitialActions.js
var InitialiseActions = {
initApp: function(){
Dispatcher.dispatch({
actionType: ActionTypes.INITIALISE,
initialData: {
bill: BillApi.getBillLocal() // I switch to getBillServer for date from server
}
});
}
};
module.exports = InitialiseActions;
然后我的数据 API 看起来像这样
api.js
var BillApi = {
getBillLocal: function() {
return billed;
},
getBillServer: function() {
return $.getJSON('https://theurl.com/stuff.json').then(function(data) {
return data;
});
}
};
module.exports = BillApi;
这就是商店 store.js
var _bill = [];
var BillStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
getAllBill: function() {
return _bill;
}
});
Dispatcher.register(function(action){
switch(action.actionType){
case ActionTypes.INITIALISE:
_bill = action.initialData.bill;
BillStore.emitChange();
break;
default:
// do nothing
}
});
module.exports = BillStore;
正如我之前提到的,当我在操作中使用 BillApi.getBillLocal() 在本地加载数据时,一切正常。但是当我更改为 BillApi.getBillServer() 时,我在控制台中收到以下错误...
Warning: Failed propType: Required prop `subscription` was not specified in `subscriptionsList`. Check the render method of `viewBill`.
Uncaught TypeError: Cannot read property 'period' of undefined
我还在 BillApi.getBillServer() 中添加了一个 console.log(data) ,我可以看到数据是从服务器返回的。但它显示在 AFTER 我在控制台中收到警告,我认为这可能是问题所在。任何人都可以提供一些建议或帮助我解决它吗?抱歉发了这么长的帖子。
更新
我对 api.js 文件进行了一些更改(在此处查看更改和 DOM 错误 plnkr.co/edit/HoXszori3HUAwUOHzPLG ),因为有人认为问题是由于我处理承诺的方式造成的。但它似乎仍然是您在 DOM 错误中看到的相同问题。
【问题讨论】:
-
subscriptionsList你在传递什么?它正在寻找this.props.subscriptions,但它不存在,所以你得到Cannot read property 'period' of undefined。我的猜测是你也有某种类型的竞争条件。 Flux 本质上是异步的…… -
我想也许这就是我收到“无法读取”错误的原因 - 因为竞争条件。数据可能还没有加载?任何提示如何解决这个问题?
-
是的,您可以使用建议的ultralame 之类的回调方法,或者您可以给
_bill一个默认对象,例如var _bill = { subscriptions: [] },所以当您执行getInitialState时,您只需通过billstore.getAllBill()。然后当组件挂载时,数据被获取,存储将发出更改并更新您的状态
标签: reactjs reactjs-flux