How do I reload a page with react-router?

后端 未结 13 1768
臣服心动
臣服心动 2020-12-09 08:23

I can see in this file (https://github.com/ReactTraining/react-router/blob/v0.13.3/modules/createRouter.js) that there is a refresh function but I have no idea how to call i

相关标签:
13条回答
  • 2020-12-09 09:07

    You can use this function.

    function reloadPage(){ 
        window.location.reload(); 
    }
    <input type="button" onClick={ reloadPage }  value="reload"/>

    0 讨论(0)
  • 2020-12-09 09:09

    If you want to use <Link/> to reload some route, or simply have single history push, you can setup <Redirect/> route under <Switch/> like this:

    <Switch>
        <Route exact path="/some-route" component={SomeRoute} />
        <Redirect exact from="/some-route/reload" to="/some-route" />
    </Switch>
    

    And then <Link to="/some-route/reload" /> or push("/some-route/reload")

    0 讨论(0)
  • 2020-12-09 09:12

    This solution won't cause the undesired full page reload but requires you to make this modification to each page that needs refreshing:

    export const Page = () => {
       const location = useLocation();
       return <PageImpl key={location.key} />
    }
    

    So the idea is: create a wrapper around your page and make React re-create the actual page every time the location key changes.

    Now it's enough to call history.push(/this-page-route) again and the page refreshes.

    0 讨论(0)
  • 2020-12-09 09:13

    If you don't want to reload all scripts again you can replace the current path with a fake/empty path and replace it again with the current path like this

    // ...
    let currentPath = window.location.pathname;
    history.replace('/your-empty-route');
    setTimeout(() => {
        history.replace(currentPath)
    }, 0)
    // ...
    

    Update:

    If the changing of the address bar bothering, you can add a patterned route like this:

    <Route path="/*/reload" component={null}/>
    

    and add /replace to the end of currentPath to replace the router with null component. like this:

    // ...
    let currentPath = window.location.pathname;
    history.replace(`${currentPath}/replace`);
    setTimeout(() => {
        history.replace(currentPath)
    }, 0)
    // ...
    

    In this way, the reload keyword will add to the end of your current path and I think it's more user friendly.

    Notice: If you already have a route that ends with replace It will cause conflict. To solve that you should change the path of the patterned route to something else.

    0 讨论(0)
  • 2020-12-09 09:14

    May be you are trying to push in history object, then bind your component with withrouter or use window.location.href = url to redirect ..

    0 讨论(0)
  • 2020-12-09 09:16

    You could try this workaround:

    // I just wanted to reload a /messages page
    history.pushState(null, '/');
    history.pushState(null, '/messages');
    
    0 讨论(0)
提交回复
热议问题