[英]How do i update the rendered data of a react component?
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: 在路由器中,我设置了post组件以这种方式呈现:
<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: 然后,在我的post组件中,我运行以下代码以使用REST API调用:
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. 这适用于第一篇文章-当我单击某篇文章时,它将带我到该篇单独的文章,但是此后,即使URL更改了,它也不会更新该组件。 I checked the state through the developer tools on chrome and realized that it doesn't update the state either.
我通过chrome上的开发人员工具检查了状态,并意识到它也不会更新状态。
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.
毕竟我是一个菜鸟。
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. 仅当组件的某些道具或状态发生变化时,Component才会重新渲染,并且如果已经挂载了componentDidMount,则不会再次调用它。 So, you can try to call the rest api through your componentDidUpdate method (when the match params changes).
因此,您可以尝试通过componentDidUpdate方法(当匹配参数发生变化时)调用rest api。
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 https://reactjs.org/docs/react-component.html#componentdidmount
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.