當我在過去完成這項工作時,模式通常會像下面的代碼一樣。以下是關於該代碼的一些注意事項:
getDataFromAPI()
顯然是一個HTTP請求或類似的東西,它會返回一個承諾,該承諾將根據您在存儲中需要的數據進行解析。當然,你可以用回調來做到這一點。
storeDataInStore()
是對調度程序的調用,該調度程序處理將數據存入商店。
的組件監聽在商店的變化,所以當你打電話getDataFromAPI()
和storeDataInStore()
先後,該組件將聽到店裏的變化,調用handleStoreDataChange()
方法,並適當地重新渲染。
import LoadingComponent from './LoadingComponent';
import Store from '../../stores/ThatStore';
import { getDataFromAPI } from '../../utils/WebUtils';
import { storeDataInStore } from '../../utils/AppUtils';
class ThisComponent extends React.Component {
constructor() {
super(props);
}
componentWillMount() {
let dataFromStore = Store.getDataFromStore();
if (/* condition indicating data is in store */) {
this.setState(dataFromStore);
} else if (/* condition indicating data is not in store */) {
getDataFromAPI().then((data) => {
storeDataInStore(data);
});
}
}
componentDidMount() {
this.handleStoreDataChange = this.handleStoreDataChange.bind(this);
Store.addChangeListener(this.handleStoreDataChange);
}
componentWillUnmount() {
Store.removeChangeListener(this.handleStoreDataChange);
}
handleStoreDataChange() {
this.setState(Object.assign(Store.getDataFromStore());
}
render() {
if (/* condition indicating that you are awaiting data */) return <LoadingComponent />;
return (
/* All of the things you would render if the data is loaded in the store */
);
}
}