[英]I don't understand how components are mounted
我使用模式容器/代表組件。
我有CardContainer
組件,它從服務器獲取數據並將其傳遞給Card
組件
容器組件:
class CardContainer extends Component {
state = {
'card': null
}
componentDidMount() {
fetch(`${BASEURL}/api/cards/${this.props.params._id}/`)
.then(res => res.json())
.then(card => this.setState({'card': card}))
}
render() {
return <CardDetail card={this.state.card} />
}
代表性組成部分:
class CardDetail extends Component {
render() {
return (
<div>
{this.props.card._id}
</div>
)
}
}
在那種情況下,我有一個錯誤:
未捕獲的TypeError:無法讀取null的屬性'_id'
所以呈現前稱為孩子的方法componentDidMount
一個parrent的。
但是當我將無狀態函數組件傳遞給子節點時,一切正常:
const FunctionChild = props => <h1>{props._id}</h1>
class CardDetail extends Component {
render() {
return (
<div>
<FunctionChild {...this.props.card} />
</div>
)
}
}
我在組件render
和componentDidMount
方法中使用console.log來理解方法解析:
所以componentDidMount
仍然調用last,但一切正常。 請有人解釋我錯過了什么。
原因是,最初您將卡值定義為null
,並訪問id的值,這就是它拋出錯誤的原因:
無法訪問屬性id為null
因為你從api
獲取數據,所以它是asynchronous call
並且需要時間來return
數據,直到你沒有得到數據,卡的值將為null
。
修復此問題的一種方法是,使用{}
而不是null
初始化卡片,如下所示:
class CardContainer extends Component {
state = {
'card': {} //change this
}
componentDidMount() {
fetch(`${BASEURL}/api/cards/${this.props.params._id}/`)
.then(res => res.json())
.then(card => this.setState({'card': card}))
}
render() {
return <CardDetail card={this.state.card} />
}
或者在訪問id值之前將檢查放在子組件中,如下所示:
class CardDetail extends Component {
render() {
return (
<div>
{this.props.card && this.props.card._id}
</div>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.