【发布时间】:2017-11-11 11:18:47
【问题描述】:
我有一个名为“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 也会运行。
例如,即使我删除了第二项,我也可以看到第二项的承诺仍在运行。
unmounted
PROMISE COMPLETED 1
PROMISE COMPLETED 2
PROMISE COMPLETED 3
卸载组件时我必须取消承诺。
【问题讨论】:
-
您是否只尝试在
this.prom调用Promise构造函数一次? -
不确定我是否完全理解这个问题,但this fiddle 有帮助吗?第 8 行和第 28 行是要查看的行
标签: reactjs promise cancellation