React leaves the page to clear the data

react clears the data of the current page when it leaves the page

related codes

routerWillLeave () {

this.setState({
    myData: [],
    codeFile: [],
})

}

window.onbeforeunload = function (e) {

    e = e || window.event;
 
    if (e) {
      e.returnValue = "";
      this.setState({
          myData: []
      })
      codeFileInfo = {}
    }
  
    return "";
  };

neither of these two methods works. How should I solve it

?
Nov.20,2021

your onbeforeunload callback uses anonymous function declarations, so this points to window, here either you change the callback to the arrow function of (e) = > {} , or you assign this to a variable before you use it.

so onbeforeunload should be executed when the page closes or jumps out, but it does not affect React, due to this . At this time, console should report an error. You can check it in order to further sort out the problem.


componentWillUnmount () {
.dosth
}


I use the function componentWillReceiveProps and add some business logic judgments to make all sate empty every time the page props changes.

Menu