我使用模式容器/表示组件。
我有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之前调用子级的渲染方法。
但是,当我将无状态函数组件传递给孩子时,一切正常:

const FunctionChild = props => <h1>{props._id}</h1>

class CardDetail extends Component {
    render() {
        return (
            <div>
                <FunctionChild {...this.props.card} />
            </div>
        )
    }
}


我在组件rendercomponentDidMount方法中使用console.log来了解方法解析:


安装容器
登上孩子
挂载功能儿童
DidMount容器方法


因此componentDidMount仍被称为last,但是一切正常。请有人解释我在想什么。

最佳答案

原因是,最初将卡的值定义为null,然后访问id的值,这就是它引发错误的原因:


  无法访问null的属性ID


因为您要从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>
        )
    }
}

关于javascript - 我不明白如何安装组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43272823/

10-12 01:25
查看更多