首页 > 解决方案 > 异步选择反应不加载选项

问题描述

我正在尝试使用 React-Select 动态加载选择字段的选项。这是我在 Select 中返回 loadOptions 的方法。

 onChange(e)  {
    console.log("Value Printed : " + e);
 if(e.length > 3) {


 new Promise(resolve => {
    setTimeout(() => {           
    const url = `http://localhost:3010/cityNames?name=${e}`;
    fetch(url)
   .then(results => results.json())
   .then(data => {        
       var options = [];    
        options = data;
        console.log("return value from server: " + JSON.stringify(data));
        return {options: data};
   });
    }, 1000);
});

} else {console.log("Enter 3 chars");}
};

但我的选项没有显示。

这是渲染组件。

   <AsyncSelect
    isClearable
    loadOptions={this.onChange}
    onInputChange={this.onChange}
   />

控制台日志显示正确的结果。我的数据变量是:

 [{"label":"Dallas","value":680780}]

标签: reactjsreact-select

解决方案


显然,您的组件在获取数据时不会重新呈现。尝试改用状态。

.then((data) => {      
    this.setState({ options: data });
});

内部渲染:

<Select
   isClearable
   options={this.state.options}
   onInputChange={this.onChange}
/>

顺便说一句,我真的怀疑你必须使用 Async React Select。我认为正常的就足够了,只需稍微改变一下逻辑即可。

您的代码应如下所示:

onChange = (inputValue) => {
  if (inputValue.length > 3) {
      const url = `http://localhost:3010/cityNames?name=${inputValue}`;
        fetch(url)
          .then(results => results.json())
          .then(data => {
             this.setState({
                options: data,
             });
          });
    });
};

推荐阅读