处理Component中的Null对象属性值

时间:2017-12-19 01:49:34

标签: reactjs

我正在尝试确定处理用户可能没有定义附加到我的组件中使用的JSON对象的值的实例的最佳方法。我是否应该使用第三级命令来处理null存在的实例并抛出错误以防止我的组件加载?这些场景是否有最佳实践?

const RecordCard = props => {
    return (
            <div className="record-container">
                <RecordDate type={props.type} date={props.recordDateSlug} />
                <RecordHead linkId={props.recordIdHash} title={props.title} category={props.category.categoryName} user={props.synotate_user.fullNameSlug} picture={props.synotate_user.picture} dataDate={props.dataDateRangeSlug}/>
                <hr />
                <RecordBody discovery={props.discovery} />
                <RecordFooter reports={props.record_reports} files={props.record_files}/>
                <EditRecord linkId={props.recordIdHash} recordUser={props.user} user={props.user.userId} />
                <hr />
            </div>
    )
}

我的category={props.category.categoryName}会抛出错误:

Uncaught TypeError: Cannot read property 'categoryName' of null

1 个答案:

答案 0 :(得分:0)

一种很好的方法是使用destructuring和默认值。 category默认为空对象(如果不存在),然后categoryName将是未定义的并且不会抛出错误:

const RecordCard = ({
  category: {
    categoryName
  } = {},
  synotate_user: {
    fullNameSlug,
    picture
  } = {},
  user,
  dataDateRangeSlug,
  title,
  recordIdHash,
  type,
  recordDateSlug,
  discovery,
  record_reports,
  record_files
}) => {
  const {
    userId
  } = user;
  return (
    <div className="record-container">
      <RecordDate type={type} date={recordDateSlug} />
      <RecordHead linkId={recordIdHash} title={title} category={categoryName} user={fullNameSlug} picture={picture} dataDate={dataDateRangeSlug}/>
      <hr />
      <RecordBody discovery={discovery} />
      <RecordFooter reports={record_reports} files={record_files}/>
      <EditRecord linkId={recordIdHash} recordUser={user} user={userId} />
      <hr />
    </div>
  );
}