讓我們在底部開始:
它看起來像一個可行的選項,以使店火在動作處理HTTP請求,之後過渡到下一個狀態。但是這會使這個動作隱式地啓動HTTP調用,這會禁用完全可能性,以便具有用於調試的可重放日誌。
如果您處於調試/重放模式,則可以通過不啓動HTTP請求來緩解此問題。只要您在HTTP請求處理程序中執行的唯一的一件事是激發操作(例如SUCCESS
和FAILURE
操作),此工作將非常有效。你可以用一個簡單的全局布爾值(if (!debug) { httpReq(...) }
)來實現這個,但是你也可以讓這個模式更正式。
在Event Sourcing的說法中,您使用Gateways出於此目的。在正常操作中,網關發出HTTP請求,並在調試時關閉網關(因此它不發出任何HTTP請求)。
這就是說,我認爲這個問題實際上可以通過重新考慮你的HTTP請求的位置來解決。
因此,基本上,基於用戶與視圖的交互,ACTION被調度。商店擁有關於如何從給定ACTION的當前狀態0轉換到下一個狀態1的邏輯。需要state1的數據才能正確形成新的HTTP請求。
在你的問題(Where should ajax request be made in Flux app?),I recommend第二環節做你寫在行動創造者,但讀取在商店。如果推斷該模式爲你的使用情況,你可能最終得到這樣的(僞代碼和長變量名的清晰度):
class DataTable extends React.Component {
render() {
// Assuming that the store for the data table contains two sets of data:
// one for the filter selection and one for the pagination.
// I'll assume they're passed as props here; this also assumes that
// this component is somehow re-rendered when the store changes.
var filter = this.props.filter;
var start = this.props.start;
var end = this.props.end;
var data = this.props.dataTableStore.getDataForPageAndFilter(
start, end, filter
);
// the store will either give us the LOADING_TOKEN,
// which indicates that the data is still loading,
// or it will give us the loaded data
if (data === DataTableStore.LOADING_TOKEN) {
return this.renderLoading();
} else {
return this.renderData(data);
}
}
}
class DataTableStore {
constructor() {
this.cache = {};
this.filter = null;
this.start = 0;
this.end = 10;
}
getDataForPageAndFilter(start, end, filter) {
var url = HttpApiGateway.urlForPageAndFilter(start, end, filter);
// in a better implementation, the HttpApiGateway
// might do the caching automatically, rather than
// making the store keep the cache
if (!this.cache[url]) {
this.cache[url] = DataTableStore.LOADING_TOKEN;
HttpApiGateway.query(url)
.then((response) => {
// success
var payload = {
url: url,
data: response.body
};
dispatch(DATA_FETCH_SUCCESS, payload);
}, (error) => {
// error
dispatch(DATA_FETCH_FAIL, { ... });
});
}
return this.cache[url];
}
handleChangeFilterAction(action) {
this.filter = action.payload.filter;
// the store also decides to reset pagination
this.start = 0;
this.end = 10;
this.emit("change");
}
handleDataFetchSuccessAction(action) {
this.cache[action.payload.url] = data;
this.emit("change");
}
handleDataFetchFailAction(action) {
// ...
}
}
DataTableStore.LOADING_TOKEN = "LOADING"; // some unique value; Symbols work well
你可以看到,店裏負責決定如何更新分頁和過濾器變量,但不負責決定何時發出HTTP請求。相反,該視圖只是請求一些數據,並且如果商店沒有在緩存中,它將,然後發出HTTP請求。
這也允許視圖將任何其他本地狀態傳入getter(在HTTP請求也取決於本地狀態的情況下)。