Tag Archives: Wang Zhe’s daily summary

Click the button to use in the react project window.open Methods open a new page and click the data again

Problem description
When use the react to do background management program, there is a demand, a list can be according to the conditions of the query, there is a printing function, print is the data of the current query conditions, click on the print button, use the window. The open () method to open the new page, and set the position of open the window, to print the data in a new window display, the real printing function is realized in a new window.

at this time there is a problem, to print the data I am existing in localstorage, when the first open new window, click on the print button to print the data is correct, but if I open the window, not closing new from the previous page to change the terms of the query, click print again, open the last failed to shut down the page, the page does not automatically refresh, also won’t get the latest localstorage inside the value of the printed data is not new.

When I wrote window.location.href directly in componentDidMount, since componentDidMount is the life cycle that executes after the page has been loaded, and the page refresh cycle will be infinite, so this method does not work. I want to try to add a judgment condition, such as whether a value exists in localStorage is equal, but after the value in localStorage changes, both pages will change, so it will always be equal.
Finally, I changed an idea and found a way to listen for changes in the value of localStorage. In a new window, I can listen for changes in the value of localStorage stored in the previous page. If there is any change, I will perform the operation of refreshing the page.

window.addEventListener("storage", function(e) {
    console.log(e)
    window.location.reload()
});

Different files in the same domain will detect changes in stored values. Same file, store value changes, cannot be monitored.
the operation to store the data can be placed at the click of the print button to open the new page, so that the data in the new window does not change until after the click
For this problem, there should be other solutions, thank you added.