问题
I am reloading a Component via Redirect from react-router-dom v4, When the Component loads for the first time the api calls occur within ComponentDidMount. But this method doesn't run when component reload is triggered by Redirect.
I have the component TopicList , which is displayed by the path /topic using Route from react-router-dom
PostTopic is a Modal that is rendered within TopicList. Inside PostTopic , i add a property called redirect, to the state, and use this to render a Redirect Component to="/topic", I redirect after posting some data to the api.
In topicList when it reloads via Redirect, componentDidMount() is not running so the api call to fetch the newly posted data does not occur.
What is the best way to refetch data from an api call, after reloading the same route via Redirect from react-router.
class PostTopic extends Component
state = {
redirect: false
}
handleSubmit = (e) => {
e.preventDefault();
const { body, subject } = this.state;
api.postTopic(this.props.store.token,subject,body)
.then( response => {
this.setState({redirect:true})
})
.catch( error => {
this.setState({error});
});
}
renderRedirect = () => {
if(this.state.redirect){
return <Redirect to={this.props.currentPath}/>
}
}
render(){
return(
...
...
...
{this.renderRedirect()}
}
}
回答1:
componentDidMount
will only be run when the component is initially mounted in the DOM, and when a URL parameter changes a new component is not mounted.
You need to use componentDidUpdate
and check if the URL parameter has changed and fetch your data again if that is the case.
Example
function getData() {
return new Promise(resolve => {
setTimeout(() => {
resolve(Array.from({ length: 3 }, () => Math.random()));
}, 1000);
});
}
class Page extends React.Component {
state = { data: [] };
componentDidMount() {
getData().then(data => {
this.setState({ data });
});
}
componentDidUpdate(prevProps) {
if (prevProps.match.params.pathParam !== this.props.match.params.pathParam) {
getData().then(data => {
this.setState({ data });
});
}
}
render() {
return (
<div>
{this.state.data.map(element => <div key={element}>{element}</div>)}
</div>
);
}
}
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<Link to="foo"> Foo </Link>
<Link to="bar"> Bar </Link>
<Switch>
<Route path="/:pathParam" component={Page} />
</Switch>
</div>
</BrowserRouter>
);
}
}
来源:https://stackoverflow.com/questions/51751075/api-call-after-reloading-same-route-via-react-router