【问题标题】:destructuring and using props in react components在反应组件中解构和使用道具
【发布时间】:2017-06-15 04:21:04
【问题描述】:

说我将 total_counts 从父组件传递给子组件。

在我的子组件中,我有一个渲染方法

render() {
    console.log(this.props.pagination.total_counts )
}

如何正确使用 total_counts 而不会出错?我的孩子渲染方法可能会渲染多次,因为分页是通过 http 调用来的。如果我像下面那样进行解构

const { total_counts } = this.props.pagination
render(){
   return (
      <div>{total_counts && <p>{total_counts.toString()}</p>}</div>
   )
}

我还是要检查 total_counts 是不是 undefined

【问题讨论】:

  • 你的问题到底是什么?
  • 试试const { total_counts } = this.props.pagination ?
  • @D-reaper 如果 this.props.pagination 未定义,如果我尝试渲染 total_counts,我的应用程序会中断吗?

标签: javascript reactjs jsx


【解决方案1】:

如果你是从this.props.pagination访问total_counts,那么解构语句应该是这样的:

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;
}

【讨论】:

  • 如果 this.props.pagination 未定义,如果我尝试渲染 total_counts,我的应用程序会中断吗?
  • 很可能会。因此,您必须先检查它是否未定义,如果是,则回退到某个值。
猜你喜欢
  • 1970-01-01
  • 2018-12-15
  • 2018-11-25
  • 2020-12-25
  • 1970-01-01
  • 2019-05-31
  • 2021-05-12
  • 1970-01-01
  • 2018-04-10
相关资源
最近更新 更多