Force remount component when click on the same react router Link multiple times

℡╲_俬逩灬. 提交于 2020-03-04 23:06:13

问题


I have a route page with a datatable fetch data when component mount. When I click on the same react-router-dom Link (to the route above) multiple times, it seems like component only unmount when the route change (with different component to be render).

I want the component to be forced remount when click on the same link again in order to fetch new data. Are there any options in react-router-dom Link or any other Link component or any trick to do this?

My sample code here: https://codesandbox.io/s/react-router-9wrkz

I want the About component will remount when click About link multiple times


回答1:


One way to force a component to re-mount is to change the key prop :

  <Route
    path="/about"
    render={props => <About key={Date.now()} {...props} />}
  />

https://codesandbox.io/s/react-router-6cptd




回答2:


You can use this method for rendering

componentWillReceiveProps(recievedProps) {
    console.log("componentWillReceiveProps called");
    if (
      recievedProps &&
      this.props &&
      recievedProps.location &&
      this.props.location &&
      recievedProps.location.key &&
      this.props.location.key &&
      recievedProps.location.key !== this.props.location.key
    ) {
      this.setState({ loading: true });
      promise().then(result => {
        this.setState({ value: result, loading: false });
      });
    }
  }



回答3:


Why not just force reloading onClick by creating a function in your component:

remount(){
    location.reload(true);
}

And then assign onClick handler to the Link:

<Link to="/your route" onClick = {this.remount}>

Seems to work fine unless you have objections to reloading the page.



来源:https://stackoverflow.com/questions/57786965/force-remount-component-when-click-on-the-same-react-router-link-multiple-times

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