我有一个名为“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>
        )
    }
}
如您所见,promise 在调用后 6 秒调用了 resolve。
还有另一个名为“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)
在上面的例子中,它在屏幕上显示了三个项目。
如果我删除这些组件中的任何一个,将调用 componentWillUnmount(),但也会运行在已删除组件中创建的Promise。
例如,即使我删除了第二个项目,我也可以看到第二个项目的Promise正在运行。
unmounted 
PROMISE COMPLETED 1 
PROMISE COMPLETED 2 
PROMISE COMPLETED 3
卸载组件时,我必须取消Promise。
