我在弄清楚在我的react / redux应用程序中将异步副作用处理程序粘贴到哪里时遇到了一些麻烦。
我正在使用react-router,并且我所有的根(或几乎根)级别的容器都在调用调度并毫无问题地接收更新。复杂之处在于异步服务适合于此。这是一个例子:
路线
<Route path='/' component={App}>
<Route path='/home' component={Home} />
<Route path='/locations' component={Locations} />
<Route path='/something-else' component={SomethingElse} />
</Route>
让我们看一下需要获取某些东西的地方,这并不奇怪:
class Locations extends React.Component<LocationsProps, void> {
private _service: StoreService;
constructor(props) {
super(props);
this._service = new StoreService();
}
render(): JSX.Element {
const { status, stores, selectedStore } = this.props;
return (
<fieldset>
<h1>Locations</h1>
<StoresComponent
status={status}
stores={stores}
selectedStore={selectedStore}
onFetch={this._onFetch.bind(this)}
onSelect={this._onStoreSelect.bind(this)} />
</fieldset>
);
}
private _onFetch(): void {
const { dispatch } = this.props;
dispatch(fetchStores());
this._service.find()
.then(stores => dispatch(loadStores(stores)));
}
private _onStoreSelect(id: string): void {
const { dispatch } = this.props;
dispatch(selectStore(id));
}
static contextTypes: React.ValidationMap<any> = {
status: React.PropTypes.string,
stores: React.PropTypes.arrayOf(React.PropTypes.object)
};
}
function mapStateToProps(state) {
return {
status: state.stores.status,
stores: state.stores.list,
selectedStore: state.stores.selectedStore
};
}
export default connect(mapStateToProps)(Locations);
我有一个非常笨的商店组件,它依赖于它的容器来完成大部分工作。Locations容器通常也很笨,但是困扰我的是_onFetch()
方法,它是由Stores组件内部的按钮单击触发的。
onFetch()
正在分派该操作,该操作将状态设置为“正在提取”,但它也与StoreService交互,感觉很臭。应该如何处理?这样,Locations就可以调度动作并等待其道具更新了吗?
我考虑过的
我曾考虑过将所有API交互都移至顶级“应用”容器,但这仍然感觉不太正确。是否可以将“无头”侦听器订阅到应用程序状态?也就是说,什么都不会渲染任何东西,只监视获取请求并触发类似以下内容的东西:
this._storeService.find()
.then(stores => dispatch(loadStores(stores)));
使用sagas进行任何异步,setinterval等副作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句