我有以下代码:
class TradeItemBox extends React.Component {
constructor(props) {
super(props)
console.log('tradeitembox', props)
this.removeItemsFromTrade = this.removeItemsFromTrade.bind(this)
this.onUnloadCleanup = this.onUnloadCleanup.bind(this)
}
renderItems() {
const {trade} = this.props
if (trade.items.length === 0) {
return null
}
return trade.items.map((item, key) => {
return <TradeItem key={key} item={item}/>
})
}
onUnloadCleanup() {
alert('Hello!')
console.log('unloading')
if(this.props.trade.items.length > 0) {
this.removeItemsFromTrade()
}
}
componentDidMount() {
console.log('did mount')
window.addEventListener('beforeunload', this.onUnloadCleanup)
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnloadCleanup)
}
removeItemsFromTrade() {
const {firebase, trade, removeItemFromTrade} = this.props
trade.items.forEach((item) => {
item.isTemporarilyInUse = false
item.currentUser = null
firebase.set(`/inventory/${item.id}`, item)
removeItemFromTrade(item.id)
})
}
render() {
return (
<Col xs={12} md={5}>
<div className="items-container">
{this.renderItems()}
</div>
<Button
onClick={this.removeItemsFromTrade}
disabled={!this.props.isLoggedIn}
color="success"
>
{'<= Clear trade'}
</Button>
</Col>
)
}
}
const firebaseWrappedComponent = firebase()(TradeItemBox)
const mapStateToProps = ({trade, user}) => ({
isLoggedIn: user.isLoggedIn,
trade
})
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
removeItemFromTrade
}, dispatch)
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(firebaseWrappedComponent)
我需要进行一些清理(例如,如果用户在交易中离开页面,则将某些状态恢复到Firebase),所以我在SO上阅读并发现我应该向window.beforeunload添加一个事件监听器componentDidMount并在componentWillMount中将其删除。但是,事件永远不会触发,警报永远不会出现,不会在刷新时也不会在标签退出时出现。关于为什么这不会发生的任何提示?
答案 0 :(得分:0)
您需要从分配给此事件的回调中返回一些字符串。
onUnloadCleanup() {
alert('Hello!')
console.log('unloading')
if(this.props.trade.items.length > 0) {
this.removeItemsFromTrade()
}
return "unloading";
}