React how to render page after query change in URL

Viewed 1327

I'm facing a problem :

I access a URL, for example:

http://localhost:900/user

In my page i have an array. When I click on an pagination button for change page in array, my fonction changePage is called, the URL changes for add search query, my page re render because i use setState({page}), so far so good. New URL : http://localhost:900/user?page=2 (Attention the pathname has not changed, i just add search query)

If i click on next page again, the url change to http://localhost:900/user?page=3 and my page re render. It's perfect.

Now, i press the back button in the Browser, the location changes back to http://localhost:900/user?page=2 but the page does not re render.

How to re render page if user press the back button in the Browser and not on the last page on application ?

I use :
react : "16.3.2",
react-dom : "16.3.2",
react-redux : "5.0.7",
react-router-dom : "4.2.2",

EDIT: when i use listen function after create BrowserHistory, and i press previous browser page:

const history = createBrowserHistory();
history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.search);
});

the location.search was good.

My problem is only when i use the arrows of the browser in the same page. When i go in other page and i go back to the page, the url is good to and my array is reload with the good informations

3 Answers

You can try listening on the 'popstate' event handler :

window.addEventListener("popstate", () => {
  // React state change logic
});

From MDN: The popstate event is fired when the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.

On the function you are using to route, have you tried: this.props.history.push('/{yourNewUrl}') ?

You need to put appropriate cache-control headers in your response headers -

cache-control: private, max-age=0, no-cache, no-store
Related