首页 > 解决方案 > 每个选择选项的反应 API 调用

问题描述

我有这个接收选择选项值的功能。此外,我有 3 个选择选项(级别、设施、主机)。当我选择选项时,值将发送到此函数。

private optionFilterHandler = (option: string, key: string | number) => {


// the key can be level , facility , host  
// whereas options are the values of keys
// for level option values are (debug , warning ,info etc)  
// similarly for host and facility have options values


        if (option || key) {
            this.setState({
                option: option,
                key: key,

            },
                this.filterHandler
            ); // callback function
        }

然后作为选项和键存储在状态中

问题是我需要将所有三个选项都发送到 API,例如:API 调用应该是这样的

private filterHandler = async () => {

const response: Response = await fetch(
           'http://egrde-tvm-aso1.de.egr.lan:3000/api/v1/search',
           {
               method: 'POST',
               headers: {
                   Accept: 'application/json',
                   'Content-Type': 'application/json'
               },
               body: JSON.stringify({
                facility: this.state.option,
                level: this.state.option,
                host: this.state.option
       });
       });
}

那么我应该如何在 json.Stringify({}) 中发送所有三个选项,因为每次选择选项时我只得到一个选项值以及如何检查选项值是否属于级别、设施或主机。

标签: jsonreactjstypescriptapifilter

解决方案


您可以更改您的状态以拥有一个收集所有选项的对象。然后在事件处理程序中,您可以将选项分配给属性key。此外,也许您打算在事件处理程序中使用&&而不是?||

constructor(props) {
    super(props);
    this.state = {
        options: {
            level: undefined,
            facility: undefined,
            host: undefined
        }
    };
}

private optionFilterHandler = (option: string, key: string | number) => {
    if (option && key) {
        this.setState(
            {
                options: { ...this.state.options, [key]: option }
                // copies the old options object and sets the property `key` to
                // the value `option`
                // Uses "computed property names": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
            },
            this.filterHandler
        );
    }
};

private filterHandler: Response = async () => {
    const { level, facility, host } = this.state.options
    // ⮤ object destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

    if (!level || !facility || !host) {
        // Don't fetch unless all options are present (remove this if
        // it's okay to fetch with partial options)
        return
    }

    const response = await fetch(
        'http://egrde-tvm-aso1.de.egr.lan:3000/api/v1/search',
        {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.state.options)
        }
    );
};

推荐阅读