导航离开React中的组件时中止请求

Sal*_*man 4 javascript reactjs react-router redux

我正在使用react,reduxreact-router.我的一个页面是发出API请求并显示数据.它工作正常.我想知道的是,如果API请求尚未完成,并且用户导航到另一个路由,我希望能够中止请求.

我假设我应该派出一些行动componentWillUnmount.只是无法理解它将如何运作.就像是...

componentWillUnmount() {
    this.props.dispatch(Actions.abortRequest());
}
Run Code Online (Sandbox Code Playgroud)

我会xhr在动作的某处存储引用.不确定这是否是正确的方法(我认为不是),有人能指出我正确的方向吗?

Dan*_*mov 8

我不认为存储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() };     
  };
}
Run Code Online (Sandbox Code Playgroud)

现在您可以abort在组件中使用:

componentDidMount() {
  this.requests = [];
  this.requests.push(
    this.props.dispatch(fetchPost(this.props.postId))
  );
}

componentWillUnmount() {
  this.requests.forEach(request => request.abort());
}
Run Code Online (Sandbox Code Playgroud)