我使用模式容器/代表性组件。
我有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>
)
}
}
在这种情况下,我有一个错误:
未捕获的类型错误:无法读取 null 的属性“_id”
因此componentDidMount
,在父级之前调用的子级的渲染方法。
但是在我将无状态函数组件传递给孩子的情况下,一切正常:
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 的值,这就是它抛出错误的原因:
无法访问 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>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句