导航离开React中的组件时中止请求 [英] Abort request while navigating away from the component in React

查看:485
本文介绍了导航离开React中的组件时中止请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using react, redux and react-router. One of my page is making an API request and showing the data. It works fine. What I want to know is, if the API request is not yet finished, and the user navigates to another route, I want to be able to abort the request.

I我假设我应该在 componentWillUnmount 中发布一些动作。只是无法理解它将如何运作。类似于......

I am assuming I should dispatch some action in the componentWillUnmount. Just not able to understand how will it work. Something like...

componentWillUnmount() {
    this.props.dispatch(Actions.abortRequest());
}

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

And I'll store the xhr reference somewhere in the action. Not sure if this is the correct approach or not (I think not), can someone point me in the right direction?

推荐答案

我不认为存储 xhr 的操作是正确的。

操作应该是可序列化的,而XMLHttpRequest肯定不是。

I don't think storing xhr in action is correct.
Actions should be serializable, and XMLHttpRequest definitely isn't.

相反,我会使用 Redux Thunk 从我的动作创建者返回自定义对象,并执行以下操作:

Instead, I'd use Redux Thunk to return a custom object from my action creator, and do something like this:

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 来自你的组件:

Now you can use abort from your component:

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

componentWillUnmount() {
  this.requests.forEach(request => request.abort());
}

这篇关于导航离开React中的组件时中止请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆