说我将total_counts从parent传递给子组件。
在我的孩子组件中,我有一个渲染方法
render() {
console.log(this.props.pagination.total_counts )
}
如何正确使用total_counts而不出错?我的孩子渲染方法可能会多次渲染,因为分页是通过http调用来实现的。如果我像下面那样做了desctructring
const { total_counts } = this.props.pagination
render(){
return (
<div>{total_counts && <p>{total_counts.toString()}</p>}</div>
)
}
我仍然需要检查total_counts是否未定义
答案 0 :(得分:1)
如果您从total_counts
访问this.props.pagination
,那么解构声明应该是这样的:
const { total_counts } = this.props.pagination;
这假设分页永远不会被定义。否则,我建议你先检查它,如果它不存在则回退到某个值;
// default value if this.props.pagination is undefined
let total_counts = 0;
// if this.props.pagination and total_counts property in it exist
// then assign total_counts variable
if (this.props.pagination && this.props.pagination.total_counts) {
total_counts = this.props.pagination.total_counts;
}
&#13;