React - Page doesn't display when using the browser back button

戏子无情 提交于 2019-12-08 05:11:25

问题


I have looked through a lot of related topics and have so far been unable to resolve my problem with my MERN app.

When I try to go to another website and use the browser back button, some pages doesn't show.

Instead, I can only see my json file / API response... I need to refresh the page for it to be displayed correctly.

If, for example, you are going to : https://www.website.org/royalty-free-music/cinematic/page-1, try to go to another website and click to the go back button in your browser, the page doesn't display...

It only happend when you exit the website, go to another one and coming back with the go back button.... it doesn't happend when you stay on the website.


There is no problem with the pages:

https://www.website.org/how-to-use-our-music or https://www.website.org/license-agreement ...

It only happend for the pages like this :

https://website.com/royalty-free-music/:category/page-:page

For example:

https://www.website.org/royalty-free-music/all/page-1 or https://www.website.org/royalty-free-music/corporate/page-2


I think it might be related to the state in client/src/components/tracks/Tracks.js but I don't know what to fix....


Thank you in advance for you help (:


回答1:


This probably comes from a browser cache problem. It's a single page app using React, so you need to always go through the front app index.html. For this you correctly serve index.html on a wildcard route /* declared after your other routes, and you also use some middleware (history fallback). But as you declared the same route on the client and the server: /royalty-free-music/all/page-1 the browser may look in the cache for the response and use the one provided by the server (JSON data) instead of the one corresponding to the front application.

You may solve this problem in two ways:

  • obviously, change the server URL, or maybe prefix it with api. It would be semantically more correct (IMO) as server and front-end routes do not serve the same purpose (you are not dealing with server side rendering here)
  • disable cache on the server route by using res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private') in your route.


来源:https://stackoverflow.com/questions/56008265/react-page-doesnt-display-when-using-the-browser-back-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!