[英]Check for empty object and return boolean
I have a AddContactForm
form that allows the user to add contacts
.我有一个AddContactForm
表单,允许用户添加contacts
。
When the user fills in the conactNumber
- onBlur
it checks if this conactNumber
already exists.当用户填写conactNumber
- onBlur
它会检查这个conactNumber
已经存在。
How can I make The CheckIfContactExists
function returns either true
or false
instead of the promise object?如何让CheckIfContactExists
函数返回true
或false
而不是 promise 对象?
Please note that I can't change the returned value from the api, it only return a contact
object.请注意,我无法更改 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}`);
};
Make use of async await in checkContact just like you did for CheckIfContactExists
.在 checkContact 中使用 async await 就像你在CheckIfContactExists
所做的CheckIfContactExists
。 Also return the boolean result from CheckIfContactExits
method还从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;
}
};
You can't make it return just a boolean since it's an asynchronous operation.你不能让它只返回一个布尔值,因为它是一个异步操作。 You could make the checkContact
function async
as well and await
it.您也可以使checkContact
函数async
并await
它。
Example例子
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() {
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.