【问题标题】:React Select with Async - Failing to load optionsReact Select with Async - 无法加载选项
【发布时间】:2017-09-29 16:22:57
【问题描述】:

我正在尝试创建一个 react-select 异步输入字段,该字段根据用户输入提供型号。我的 API 正在工作,Fetch 也在工作,它正在生成填充下拉列表所需的确切“选项”对象(我检查了网络请求和控制台)。

问题是当我开始输入时,下拉菜单显示它正在加载,但没有添加任何选项。

以下是 Fetch 调用的示例输出: {options: [{value: "WA501006", label: "WA501006"}]}.

这是我的代码:

getModelsAPI = (input) => {

        if (!input) {
            return Promise.resolve({ options: [] });
        }

        const url = `(...)?cmd=item_codes_json&term=${input}`;

        fetch(url, {credentials: 'include'})
            .then((response) => {
                return response.json();
            })
            .then((json) => {
                const formatted = json.map((l) => {
                    return Object.assign({}, {
                        value: l.value,
                        label: l.label
                    });
                })
                return { options: formatted }
            })
    }

onChange = (value) => {
    this.setState({
        value: value
    })
}

<Select.Async
  value={this.state.value}
  loadOptions={this.getModelsAPI}
  placeholder="Enter Model"
  onChange={this.onChange}
/>

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    我认为你需要从getModelsAPI函数返回:

    getModelsAPI = (input) => {
    
            if (!input) {
                return Promise.resolve({ options: [] });
            }
    
            const url = `(...)?cmd=item_codes_json&term=${input}`;
    
            return fetch(url, {credentials: 'include'})
                .then((response) => {
                    return response.json();
                })
                .then((json) => {
                    const formatted = json.map((l) => {
                        return Object.assign({}, {
                            value: l.value,
                            label: l.label
                        });
                    })
                    return { options: formatted }
                })
        }
    

    【讨论】:

    • 你能解释一下为什么需要'return','getModelsAPI'的返回值不是Fetch的输出吗?
    • fetch 是一个承诺,可以与多个.then()s 链接。 fetch 内的每个 return 将值传递给下一行 .then(),但它们不会在函数外部返回。为此,您需要在整个承诺之前返回
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2022-08-10
    • 2013-08-11
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多