reactjs - 从函数中获取布尔值
问题描述
我想在运行 formValidation() 时返回一个布尔值,但目前我没有定义。奇怪的是,alert 和 console.log 工作正常。
export function formValidation(...args) {
let unfilledsObject = [];
args.map(item => {
if (this.state[item] === "" || this.state[item] === false)
unfilledsObject = [...unfilledsObject, item];
});
this.setState({ formUnfilleds: unfilledsObject }, () => {
if (this.state["formUnfilleds"].length) {
alert(
`Please fill in all neccessary fields: ${this.state.formUnfilleds}`
);
return false;
}
if (!this.state["formUnfilleds"].length) {
console.log("Validated");
return true;
}
});
}
解决方案
尝试这个:
export function formValidation({ ...args,callBack}) {
let unfilledsObject = [];
args.map(item => {
if (this.state[item] === "" || this.state[item] === false)
unfilledsObject = [...unfilledsObject, item];
});
this.setState({ formUnfilleds: unfilledsObject }, () => {
if (this.state["formUnfilleds"].length) {
alert(
`Please fill in all neccessary fields: ${this.state.formUnfilleds}`
);
callBack(false);
}
if (!this.state["formUnfilleds"].length) {
console.log("Validated");
callBack(true);
}
});
}
formValidation({... , boolean => console.log(boolean) }); // ---> you have access to the boolean in callack;
您只从回调中返回数据,而不是从 formValidation 函数范围返回数据。我使用回调
你也可以使用 Promise。有关羽毛信息,请查看此链接
推荐阅读
- c# - 使用没有证书文件的 TLS 连接到 MariaDB
- python - MongoDB 副本集 - 连接时出现错误“提供节点名或服务名,或未知”
- node.js - 将数据从服务器(Node.js)发送到 GraphQL 服务器中的客户端(React 组件)
- sql - 从同一行获取非空日期的计数
- python - 使用开始和结束日期左连接
- arrays - 循环遍历数组并根据先前的循环条件设置标志
- python - 电报 API:如何通过电报联系并使用 python @TelethonUpdates 获取状态
- javascript - 单个页面中的多个反应应用程序并使它们保持同步
- python - 有没有更好的方法在 python 中编写嵌套的 if 语句?
- python - 聚类从图像中提取的文本?