我在确定在我的 react/redux 应用程序中放置异步副作用处理程序的位置时遇到了一些麻烦。
我正在使用 react-router,我所有的根(或几乎根)级别的容器都在毫无问题地调用分派(dispatch)和接收更新。复杂之处在于异步服务适合于此。这是一个例子:
路线
<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()
正在分派(dispatch)该操作,它将状态设置为“正在获取”,但它也在与 StoreService 交互,感觉很臭。 应该如何处理?这样 Locations 就可以分派(dispatch) action 并等待其 props 更新?
我考虑过的
我考虑过将所有 API 交互移动到顶级“app”容器,但感觉仍然不太合适。是否可以订阅应用程序状态的“ headless ”监听器?即不渲染任何东西,只监视获取请求并触发类似的东西:
this._storeService.find()
.then(stores => dispatch(loadStores(stores)));
最佳答案
使用 sagas 做任何副作用,如异步、setinterval 等。
关于javascript - 如何处理 react/redux 中的副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755941/