如果卸载/重用React组件,如何在Promise中取消下一个'then'?

tom*_*ing 5 javascript promise ecmascript-6 reactjs

我试图在卸载/重用React组件时取消承诺.现在我正面临一个问题,我可以在下面的小图中更好地解释:

**Promise必须完成(执行AJAX请求并相应地更新redux存储)

创建组件=> Mounted => _onClick()fired => Promise starts =>组件已卸载但已被回收=> Promise finished =>在回收组件中调用setState()并从前一个组件中以错误状态重新呈现.

如何取消/中断/停止下一个'然后'但仍执行Promise?

...
    _onClick() {
        let dispatch = this.props.dispatch;

        if (!this.state.on) {
            API.On(dispatch, this.props.id).then(() => {
                this.setState({
                    on: true,
                })
            }).catch((error) => {
                this.setState({
                    on: false,
                })
            });
        } else {
            API.Off(dispatch, this.props.id).then(() => {
                this.setState({
                    on: false,
                });
            }).catch((error) => {
                this.setState({
                    on: true,
                })
            })
        }
    }
...
Run Code Online (Sandbox Code Playgroud)

Jef*_*nte -2

我在这里要做的只是向设置状态的承诺正文添加一个条件。您可以使用 React 的生命周期钩子来跟踪元素当前是否在 DOM 中。

下面是一个跟踪组件是否已安装的简单示例:

class Test extends React.Component {
  render() {
    return (<p>hello</p>);
  }

  componentDidMount () {
    this.mounted = true
    console.log(`mounted: ${this.mounted}`)
  }

  componentWillUnmount () {
    this.mounted = false
    console.log(`mounted: ${this.mounted}`)
  }
}
Run Code Online (Sandbox Code Playgroud)

实例: https: //codepen.io/jenius/pen/MmjPJV


基于此,您应该能够在您的 Promise 处理程序中添加一个简单的 if/else 来解决您的问题!

  • 使用 this.mounted 是一种反模式,请参阅:https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html (2认同)