How do I reload a page with react-router?

后端 未结 13 1767
臣服心动
臣服心动 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 08:52

    You don't really need react-router for this. You can just use location.reload:

    location.reload();
    

    Also that version of react-router you linked to is very old, I think it's linking to v1 when it's currently on v4.

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

    You can use this to refresh Current route:

    import createHistory from 'history/createBrowserHistory'
    const history = createHistory();
    history.go(0)
    
    0 讨论(0)
  • 2020-12-09 08:55

    React

    window.location.reload();
    

    working

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

    I'm using Django with React router. I added a urlpattern in Django so every mismatch url will redirect to the React router root page, it just works.

    urlpatterns += [
        url(r'^.*', yourviewclass, name='home')
    ]
    
    0 讨论(0)
  • 2020-12-09 08:57

    I guess that you're using react-router. I'll copy my answer from another post. So you have few possibilities to do that, currently my favorite way to do that is using anonymous function in component prop:

    <Switch>
      <Route exact path="/" component={()=><HomeContainer/>} />
      <Route exact path="/file/:itemPath/:refHash" component={()=><File/>} />
      <Route exact path="/:folderName" component ={()=><Folder/>}/>
    </Switch>
    

    Or if you want to refresh with current url params, you'll need extra route (reload), and play a little with router stack:

    reload = ()=>{
     const current = props.location.pathname;
     this.props.history.replace(`/reload`);
        setTimeout(() => {
          this.props.history.replace(current);
        });
    }
    
    <Switch>
      <Route path="/reload" component={null} key="reload" />
      <Route exact path="/" component={HomeContainer} />
      <Route exact path="/file/:itemPath/:refHash" component={File} />
      <Route exact path="/:folderName" component ={Folder}/>
    </Switch>
    
    <div onClick={this.reload}>Reload</div>
    
    0 讨论(0)
  • 2020-12-09 09:06

    firstly, add react-router as a dependency

    `yarn add react-router` or `npm install react-router`
    
    import { useHistory } from 'react-router'
    

    const history = useHistory()

    /////then add this to the funtion that that is called for re-rendering
    

    history.go(0)

    This causes your page to re-render automatically

    0 讨论(0)
提交回复
热议问题