react中如何判断页面刷新

onUnload(event) { 
  alert('页面刷新')
}

componentDidMount() {
  window.addEventListener("beforeunload", this.onUnload)
}

componentWillUnmount() {
   window.removeEventListener("beforeunload", this.onUnload)
}

beforeunload方法在react文件里根本不管用,后来搜到的解决方案如下:

if (window.performance) {
      if (performance.navigation.type == 1) {
        //表示页面刷新了
        sessionStorage.removeItem('couponNumber');
      }
 }

亲测有效

你可能感兴趣的:(react中如何判断页面刷新)