繁体   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