我不认为xhr
实际存储是正确的。
动作应该是可序列化的,而 XMLHttpRequest 绝对不是。
相反,我会使用Redux Thunk从我的动作创建者返回一个自定义对象,并执行以下操作:
function fetchPost(id) {
return dispatch => {
// Assuming you have a helper to make requests:
const xhr = makePostRequest(id);
dispatch({ type: 'FETCH_POST_REQUEST', response, id });
// Assuming you have a helper to attach event handlers:
trackXHR(xhr,
(response) => dispatch({ type: 'FETCH_POST_SUCCESS', response, id }),
(err) => dispatch({ type: 'FETCH_POST_FAILURE', err, id })
);
// Return an object with `abort` function to be used by component
return { abort: () => xhr.abort() };
};
}
现在您可以abort
从您的组件中使用:
componentDidMount() {
this.requests = [];
this.requests.push(
this.props.dispatch(fetchPost(this.props.postId))
);
}
componentWillUnmount() {
this.requests.forEach(request => request.abort());
}