问题
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