![](/img/trans.png)
[英]Is this the correct way to show data in React from a fetch request, if not how do I change JSX being rendered to a component?
[英]How do i update the rendered data of a react component?
我正在制作簡單的博客應用程序,並且對於通過這種方式訪問的每個帖子都有一個頁面:
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上的開發人員工具檢查了狀態,並意識到它也不會更新狀態。
我是新來的人,所以決定全職使用此小項目,所以如果我犯了一個菜鳥錯誤,請原諒。 畢竟我是一個菜鳥。
僅當組件的某些道具或狀態發生變化時,Component才會重新渲染,並且如果已經掛載了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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.