如何取消执行新动作时执行的先前动作?

How to cancel execution of a previous action upon a new action?

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

没有取消 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) 的内置功能。

然而,我建议做的是,不要在每次用户在字段中键入内容时分派昂贵的操作,而是将去抖动功能应用于您的事件处理功能。许多图书馆都提供此功能:

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

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} />);    
  }
}

另一个可能的解决方案是使用 redux-saga。有一个名为 takeLatest 的非常有用的助手,它似乎可以完成您想要完成的任务。