【发布时间】:2020-06-23 16:21:51
【问题描述】:
如何在 React/Redux 中创建新请求时取消之前的 axios 请求?
这是我在 Google 上找到的选项之一,但它不起作用。
action.js
class FilmsActions {
getFilmList(searchParams = undefined, cancelToken = null) {
return async dispatch => {
dispatch(filmsFetchRequest());
try {
const res = await api.get(`/films/${searchParams && searchParams}`, {
cancelToken,
});
return setTimeout(() => dispatch(filmsFetchSuccess(res.data)), 1000);
} catch (err) {
return setTimeout(() => dispatch(filmsFetchError(err)), 1000);
}
}
}
}
export const filmsActions = new FilmsActions();
app.js
import axios from 'axios';
class BrowseFilms extends Component {
...
componentDidUpdate(prevProps) {
const {
getFilmList,
location,
loading,
} = this.props;
if (prevProps.location.search !== location.search) {
if (loading) {
this.source.cancel();
}
this.source = axios.CancelToken.source();
getFilmList(location.search, this.source.token);
}
}
...
}
const mapStateToProps = state => ({
data: state.films.data,
loading: state.films.loading,
});
const mapDispatchToProps = dispatch => ({
getFilmList: (searchParams, cancelToken) => dispatch(filmsActions.getFilmList(searchParams, cancelToken)),
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(BrowseFilms));
在这种情况下,它不会取消请求。如果你交换(在 componentDidUpdate 中)if (loading) 和 this.source,那么它将取消请求,但会取消下一个请求,而不是上一个请求。
【问题讨论】:
标签: reactjs react-redux axios