Reputation: 566
I am making simple blog application, and i have a page for every individual post that is accessed this way:
http://localhost:3015/Post/post_id
And in the router i have set up the post component to render in this way:
<Route component={Post} path="/Post/post_id"></Route>
Then, in my post component i run the following code to make a call to the REST api im using:
componentDidMount(){
let id = this.props.match.params.post_id
axios.get('https://jsonplaceholder.typicode.com/posts/' + id)
.then(res => {this.setState({ //res is short for responce
post: res.data
})
})
this.setState({
id: id
})
}
And this works for the first post - when i click on a post it takes me to that individual post but after that, even though the URL changes, it doesnt update the component. I checked the state through the developer tools on chrome and realized that it doesn't update the state either.
Im new to react, and decided to take on this small project before using it full time, so excuse me if i made a rookie mistake. After all i am a rookie.
Upvotes: 0
Views: 116
Reputation: 2836
Component will re-render only if some of his props or state changes, and if it's already mounted, componentDidMount it's not called again. So, you can try to call the rest api through your componentDidUpdate method (when the match params changes).
componentDidUpdate() {
if (this.props.match.params.post_id != this.state.id) {
// make the http call and update id, and post state
}
}
https://reactjs.org/docs/react-component.html#componentdidmount
Upvotes: 3