我是新來的反應和流量,我很難弄清楚如何從服務器加載數據。我可以從本地文件加載相同的數據,而不會出現問題。如何在REACT和FLUX中創建API調用
信息首先我有向下傳遞初始狀態的視圖此控制器視圖(控制器view.js)(view.js)
控制器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;
這是店裏因此,正如我前面提到的,當我加載數據在本地使用BillApi.getBillLocal()的行動,一切工作正常 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.getBillServer()我得到在控制檯中followind錯誤...
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
我還添加了的console.log(數據)BillApi.getBillServer(),我可以看到,數據從服務器返回。但它顯示AFTER我得到的控制檯,我認爲可能是問題的警告。任何人都可以提供一些建議或幫助我解決它?對不起,這麼長的帖子。
UPDATE
我做了一些更改api.js文件(點擊此處變革和DOM錯誤plnkr.co/edit/HoXszori3HUAwUOHzPLG),因爲它是建議,這個問題是由於我如何處理承諾。但它仍然是你在DOM錯誤中看到的同樣的問題。
你在傳遞什麼'subscriptionsList'?它正在尋找'this.props.subscriptions',並且它不存在,所以你得到'不能讀取'undefined'屬性'時期'。我的猜測是你也有一些類型的競爭條件。通量本質上是異步的... –
我想也許多數民衆贊成爲什麼我得到'無法讀取'的錯誤 - 由於競爭條件。數據可能尚未加載?任何提示如何解決這個問題? –
是的,你可以使用superlame建議的回調方法,或者你可以給'_bill'一個默認對象,比如'var _bill = {subscriptions:[]}',所以當你執行'getInitialState'時,你只需要'bill'通過'store.getAllBill()'。那麼當組件裝入時,數據被提取,並且商店將發出更改並更新您的狀態 –