How to use react-router 4.0 to refresh current route? not reload the whole page

后端 未结 7 2179
暖寄归人
暖寄归人 2021-01-01 19:35

\'react-router-dom\' has refresh function here, but I don\'t know how to call this method, also their well formatted document doesn\'t bother to explain this.

windo

7条回答
  •  醉酒成梦
    2021-01-01 20:20

    I solved this by pushing a new route into history, then replacing that route with the current route (or the route you want to refresh). This will trigger react-router to "reload" the route without refreshing the entire page.

    if (routesEqual && forceRefresh) {
        router.push({ pathname: "/empty" });
        router.replace({ pathname: "/route-to-refresh" });
    }
    

    React router works by using your browser history to navigate without reloading the entire page. If you force a route into the history react router will detect this and reload the route. It is important to replace the empty route so that your back button does not take you to the empty route after you push it in.

    According to react-router it looks like the react router library does not support this functionality and probably never will, so you have to force the refresh in a hacky way.

提交回复
热议问题