reactjs - 异步选择反应不加载选项
问题描述
我正在尝试使用 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}]
解决方案
显然,您的组件在获取数据时不会重新呈现。尝试改用状态。
.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,
});
});
});
};
推荐阅读
- django - django中是否有任何属性或类似占位符的东西,我可以在其中编写永久文本
- c# - 将用户输入文本框中的值分配给另一个表单
- powershell - Powershell 从文件夹中的每个文件中获取前 x 行并创建示例文件
- kubernetes - Kubernetes入口502坏网关
- angular - Angular 材质表 applyFilter 方法
- oracle - 是否可以用 Rust 编写 Oracle 外部存储过程?
- regex - 使用正则表达式获取表中的所有内容 (html)
- python - numpy广播在条件下乘以?
- firebase - Flutter Firebase 如何做动态查询
- pandas - 在特定索引上将 TB 转换为 GB