如何检查合规性?

时间:2018-10-02 06:49:59

标签: javascript reactjs redux

在搜索中输入的数组中不存在现有数据时,出现错误Cannot read property 'general' of undefined。我需要做一个条件来跟踪错误?

当我尝试设置条件时,我会失败

{
   (selectUser.general === !undefined) ?

    <Grid >
       <Grid.Column mobile={16} tablet={6} computer={5}>
          <Image src={selectUser.general.avatar} />
       </Grid.Column>
    <Grid.Column mobile={16} tablet={10} computer={11}>
      <h1>{`${selectUser.general.firstName} ${selectUser.general.lastName}`}</h1>
      <h3>Position: {selectUser.job.title}</h3>
      <h3>Company: {selectUser.job.company}</h3>

      <h4>
         Contact:
         <p><Icon name='mail' size='small' /> <a href="mailto:Gerry_Hackett77@gmail.com">{selectUser.contact.email}</a></p>
         <p><Icon name='phone'  size='small' /> <a href="tel:8959840132">{selectUser.contact.phone}</a></p>
      </h4>
      <p><strong>Address:</strong> {`${selectUser.address.street}, ${selectUser.address.city}, ${selectUser.address.country}`}</p>
     </Grid.Column>
   </Grid>

   :

   <h2>Error</h2>

 }

完整代码示例here

1 个答案:

答案 0 :(得分:0)

该错误表明selectUser未定义,因此您需要像使用它之前先检查其是否存在

{
   (selectUser && selectUser.general) ?

    <Grid >
       <Grid.Column mobile={16} tablet={6} computer={5}>
          <Image src={selectUser.general.avatar} />
       </Grid.Column>
    <Grid.Column mobile={16} tablet={10} computer={11}>
      <h1>{`${selectUser.general.firstName} ${selectUser.general.lastName}`}</h1>
      <h3>Position: {selectUser.job.title}</h3>
      <h3>Company: {selectUser.job.company}</h3>

      <h4>
         Contact:
         <p><Icon name='mail' size='small' /> <a href="mailto:Gerry_Hackett77@gmail.com">{selectUser.contact.email}</a></p>
         <p><Icon name='phone'  size='small' /> <a href="tel:8959840132">{selectUser.contact.phone}</a></p>
      </h4>
      <p><strong>Address:</strong> {`${selectUser.address.street}, ${selectUser.address.city}, ${selectUser.address.country}`}</p>
     </Grid.Column>
   </Grid>

   :

   <h2>Error</h2>

 }