Javascript 如何处理react/redux中的副作用?
在我的react/redux应用程序中,我很难确定将异步副作用处理程序粘贴到何处 我使用的是react路由器,我所有的根(或几乎根)级别的容器都在调用dispatch并毫无问题地接收更新。复杂之处在于异步服务适合于此。下面是一个例子: 路线Javascript 如何处理react/redux中的副作用?,javascript,reactjs,typescript,redux,react-redux,Javascript,Reactjs,Typescript,Redux,React Redux,在我的react/redux应用程序中,我很难确定将异步副作用处理程序粘贴到何处 我使用的是react路由器,我所有的根(或几乎根)级别的容器都在调用dispatch并毫无问题地接收更新。复杂之处在于异步服务适合于此。下面是一个例子: 路线 <Route path='/' component={App}> <Route path='/home' component={Home} /> <Route path='/locations' componen
<Route path='/' component={App}>
<Route path='/home' component={Home} />
<Route path='/locations' component={Locations} />
<Route path='/something-else' component={SomethingElse} />
</Route>
使用saga可以产生任何副作用,如async、setinterval等。没有必要使用redux saga来实现副作用。Redux传奇主要专注于处理异步动作创建者,就像它的先锋替代Redux thunk一样。在React/Redux应用程序中处理副作用的最佳方法是在
componentDidMount
和action creators中处理副作用。
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);
this._storeService.find()
.then(stores => dispatch(loadStores(stores)));