【问题标题】:Check for empty object and return boolean检查空对象并返回布尔值
【发布时间】:2019-02-18 13:38:05
【问题描述】:

我有一个AddContactForm 表单,允许用户添加contacts

当用户填写conactNumber-onBlur 时,它会检查这个conactNumber 是否已经存在。

如何使CheckIfContactExists 函数返回truefalse 而不是promise 对象?

请注意,我无法更改 api 的返回值,它只返回一个 contact 对象。

export default class AddContactForm extends Component {
  state = {
   ...
  };

  checkContact = () => {
    const { contactNumber } = this.state.newContactInfo;
    CheckIfContactExists(contactNumber); //return promise
  };

 render() {
   ...
    return (  
       ...
   );
  }
}

const CheckIfContactExists = async searchString => {
  const { data: contactsInfo } = await axios.get(`api/Contacts/SearchContact?contactNum=${searchString}`);
};

【问题讨论】:

  • 你不能,这就是他们返回承诺的异步调用的事情,你可以将它的承诺转为布尔值,但它仍然是一个承诺

标签: javascript reactjs


【解决方案1】:

你不能让它只返回一个布尔值,因为它是一个异步操作。您也可以将checkContact 函数设为asyncawait

示例

export default class AddContactForm extends Component {
  state = {
   // ...
  };

  checkContact = async () => {
    const { contactNumber } = this.state.newContactInfo;
    const contactInfo = await CheckIfContactExists(contactNumber);

    this.setState({
      contactNumberTaken: Object.keys(contactInfo).length !== 0
    });
  };

  render() {
    // ...
  }
}

【讨论】:

  • 感谢您的回答,但Boolean(contactsInfo) 将始终返回true,未分配任何属性的对象不被视为“空”。
  • @user3378165 是的。我更新了答案,检查它是否是返回的空对象。
【解决方案2】:

就像在CheckIfContactExists 中一样,在 checkContact 中使用异步等待。还从CheckIfContactExits 方法返回布尔结果

export default class AddContactForm extends Component {
  state = {
   ...
  };

  checkContact = async () => {
    const { contactNumber } = this.state.newContactInfo;
    try {
      const res = await CheckIfContactExists(contactNumber); 
      return res;
    } catch (e) {
       console.log('Error', error);
    }
  };

 render() {
   ...
    return (  
       ...
   );
  }
}

const CheckIfContactExists = async searchString => {
  const { data: contactsInfo } = await axios.get(`api/Contacts/SearchContact?contactNum=${searchString}`);
  if (Object.keys(contactsInfo).length > 0) {
     return true;
  } else {
      return false;
  }
};

【讨论】:

  • 感谢您的回答,但if (contactsInfo) 将始终返回true,未分配任何属性的对象不被视为“空”。
  • 在这种情况下,您可以简单地检查对象键的大小。我写答案时的假设是,如果未找到,contactsInfo 将返回 undefined 或 null
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2019-10-09
相关资源
最近更新 更多