0
我正在嘗試在應用程序中創建一個狀態組件,這將在數據獲取和其他網絡相關事件期間進行更新。在數據獲取期間更新負責顯示狀態的組件的狀態
componentWillReceiveProps(nextProps){
// This check is required otherwise setting state
// from here will end up in a rendering loop
if(!_.isEqual(this.props, nextProps)){
if(nextProps.services.length != 0){
if(nextProps.filters.length == 0){
nextProps.setStatus('Fetching filters...');
const { serviceId } = nextProps.params;
const serviceIndex = nextProps
.services
.findIndex(
(service) => service.id == serviceId
);
const serviceObj = nextProps.services[serviceIndex];
nextProps.getFilters(serviceObj);
}
}
}
} 這裏我使用componentWillReceiveProps生命週期事件加載基於店內另一組數據的一些數據(由於依賴)。 setStatus方法負責使用新的狀態消息更新商店,並根據該狀態組件將被更新。在這裏你可以看到,我正在檢查過濾器是否爲空,我正在設置狀態並試圖獲取數據。現在,當我設置狀態時,它正在更新商店,從而再次啓動「渲染」過程。這將再次調用生命週期事件,並且由於過濾器仍爲空,它將再次執行數據提取請求。目前,我已停止使用這種方法
// Setting status will set the state and invoke data collection
// again as filters are still empty due to re-render
if(_.isEqual(this.props.status,nextProps.status) &&
_.isEqual(this.props.filters,nextProps.filters)) {
const { serviceId } = nextProps.params;
const serviceIndex = nextProps
.services
.findIndex(
(service) => service.id == serviceId
);
const serviceObj = nextProps.services[serviceIndex];
nextProps.getFilters(serviceObj);
}
但是這種方法更像是一種黑客攻擊。你能否建議爲這個狀態組件提供更好的設計方法?我可以維護一個受控組件嗎?
我只通過redux商店跟蹤「狀態」,但那是爲我造成麻煩的原因。我試圖通知用戶,我正試圖從服務器獲取數據,爲了做到這一點,我正在更新商店並再次執行渲染過程。這個下一個渲染會重新發送請求到服務器,因爲過濾器部分(在這個例子中)仍然是空的,這被認爲是獲取數據以填補數據的一個步驟。 –