React Select with Async - 无法加载选项

Avr*_*zky 4 reactjs react-select

我正在尝试创建一个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}
/>
Run Code Online (Sandbox Code Playgroud)

Dor*_*man 5

我认为你需要从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 }
            })
    }
Run Code Online (Sandbox Code Playgroud)

  • `fetch` 是一个 promise,可以链接多个 `.then()`。`fetch` 内的每个 return 都将值传递给下一个 `.then()`,但它们不会在函数外返回。为此,您需要在整个承诺之前返回 (2认同)