在ReactJS中卸载组件时取消承诺

amo*_*one 12 promise cancellation reactjs

我有一个名为"Item"的组件,它在挂载时创建并调用promise.

class Item extends React.Component{
    constructor(props){
        super(props)
        this.onClick = this.onClick.bind(this)

        this.prom = new Promise((resolve, reject) => {
            setTimeout(() => resolve("PROMISE COMPLETED "+this.props.id),6000)
        })
    }

    componentDidMount(){
        this.prom.then((success) => {
            console.log(success)
        })
    }

    componentWillUnmount(){
       console.log("unmounted")
    }

    onClick(e){
        e.preventDefault()
        this.props.remove(this.props.id)
    }

    render(){
        return (
            <h1>Item {this.props.id} - <a href="#" onClick={this.onClick}>Remove</a></h1>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,promise在调用后6秒调用解析.

另一个名为"List"的组件负责在屏幕上显示这些项目."List"是"Item"组件的父级.

class List extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            items : [1,2,3]
        }

        this.handleRemove = this.handleRemove.bind(this)
    }

    handleRemove(id){
        this.setState((prevState, props) => ({
            items : prevState.items.filter((cId) => cId != id)
        }));
    }

    render(){
        return (
            <div>
            {this.state.items.map((item) => (
                <Item key={item} id={item} remove={this.handleRemove}  />
            ))
            }
            </div>
        )
    }
}

ReactDOM.render(<List />,root)
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,它在屏幕上显示三个项目.

在此输入图像描述

如果我删除任何这些组件,则会调用componentWillUnmount(),但也会运行已删除组件中创建的promise.

例如,即使我删除第二项,我也可以看到第二项的承诺.

unmounted 
PROMISE COMPLETED 1 
PROMISE COMPLETED 2 
PROMISE COMPLETED 3
Run Code Online (Sandbox Code Playgroud)

卸载组件时,我必须取消承诺.

小智 1

你无法取消原生 ES6 承诺。了解更多信息https://medium.com/@benlesh/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082

然而,您可以做的是使用非本地承诺库,例如BluebirdQ,它们为您提供可以取消的承诺。