如何在新动作上取消先前动作的执行? [英] How to cancel execution of a previous action upon a new action?

查看:52
本文介绍了如何在新动作上取消先前动作的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作创建者,它进行昂贵的计算并在每次用户输入内容时分派动作(基本上是实时更新).但是,如果用户输入多个内容,我不希望之前的昂贵计算完全运行.理想情况下,我希望能够取消先前计算的执行并只执行当前计算.

I have an action creator which does an expensive calculation and dispatches an action every time the user inputs something (basically real time updating). However, if the user inputs multiple things, I don't want the prior expensive calculations to fully run. Ideally I want to be able to cancel execution of the previous calculations and just do the current one.

推荐答案

没有内置功能可以取消 Promise 在异步操作中.如果您使用 AJAX 请求,您可以尝试手动实现取消,但是,如果您使用 Fetch API(正在讨论添加此功能这里a>).

There's no built-in feature to cancel a Promise in an asynchronous action. You can try manually implement cancellation if you're using AJAX requests, however, it's not possible if you're using Fetch API (there's an ongoing discussion about adding this feature here).

然而,我建议您不要在每次用户在字段中输入内容时分派昂贵的操作,而是将去抖动功能应用于您的事件处理功能.许多库中都有此函数:

What I would suggest to do, however, instead of dispatching an expensive action every time a user types in something in a field, apply debouncing function to your event handling function. This function is available in many libraries:

这会延迟分派动作,直到自上次分派此动作以来经过了一定的毫秒数.它将大大减少大量繁重的异步操作,因为操作将被分派,比如说,每 500 毫秒或 1 秒取决于您的配置,而不是每个更改事件.

This would delay dispatching an action until a certain number of milliseconds have elapsed since the last time this action was dispatched. It will drastically reduce a number of heavy asynchronous operations since the action will be dispatched, let's say, every 500ms or 1s depend on your configuration instead of on every change event.

使用 lodash 实现的示例:

class MyComponent extends React.Component {

  constructor() {
    // Create a debounced function
    this.onChangeDelayed = _.debounce(this.onChange, 500);
  }

  onChange() {
    this.props.onChange(); // Function that dispatches an action
  }

  render() {
    return (<input type="text" onChange={this.onChangeDelayed} />);    
  }
}

这篇关于如何在新动作上取消先前动作的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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