首页 > 解决方案 > 从函数中获取布尔值

问题描述

我想在运行 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;
        }
    });
}

标签: reactjs

解决方案


尝试这个:

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。有关羽毛信息,请查看此链接


推荐阅读