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

时间:2015-10-02 06:10:21

标签: javascript reactjs react-router redux

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

我假设我应该在componentWillUnmount发送一些动作。只是无法理解它将如何运作。有点像...

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

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

2 个答案:

答案 0 :(得分: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() };     
  };
}

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

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

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

答案 1 :(得分:2)

我认为这种方法没有任何问题。您在store中持有的是全局应用程序状态;如果您想根据其他操作更改xhr行为,则需要将该状态存储在某处。

我见过很多商店看起来像这样的例子:

{
  isFetching: false,
  items: [],
  lastUpdated: null
};

然后使用isFetching状态显示加载微调器或阻止发送多个xhr请求。我会看到你使用和存储xhr引用并且能够中止它只是这个的扩展。

相关问题