簡體   English   中英

我不明白組件是如何安裝的

[英]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>
        )
    }
}

我在組件rendercomponentDidMount方法中使用console.log來理解方法解析:

  1. 裝載容器
  2. 裝載孩子
  3. 掛載功能孩子
  4. DidMount容器方法

所以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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM