我正在制作简单的博客应用程序,并且对于通过这种方式访问的每个帖子,我都有一个页面:
http://localhost:3015/Post/post_id
在路由器中,我设置了post组件以这种方式呈现:
<Route component={Post} path="/Post/post_id"></Route>
然后,在我的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
})
}
这适用于第一篇文章-当我单击某篇文章时,将我带到该篇文章中,但是此后,即使URL更改,它也不会更新组件。我通过chrome上的开发人员工具检查了状态,并意识到它也不会更新状态。
我是新来者,所以决定全职使用此小项目,所以如果我犯了新手错误,请原谅。毕竟我是一个菜鸟。
答案 0 :(得分:3)
仅当组件的某些道具或状态发生变化,并且组件已经安装好componentDidMount时,组件才会重新渲染。因此,您可以尝试通过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