我在一个项目中使用 React-select V 2.2.x,在其中一个组件中我有 2 个相互依赖的选择选项 (第一个选择选项从远程源加载选项,当用户选择其选项之一时;第二个选择选项被激活并基于第一个选择选项值从远程源加载选项 ->所以两个都是异步的);你可以在下面看到他们的图片。 2 dependant selec-options 问题是我想将第一个选择选项值作为第二个选择选项“loadOptions”的参数传递,如下所示:
<AsyncSelect cacheOptions defaultOptions loadOptions={this.filterProvince}
id="province" className="form-field-name selector" valueKey="value"
labelKey="label" value={province} onChange={this.provinceChange} />
<AsyncSelect cacheOptions defaultOptions loadOptions={this.getCity(province)}
id="city" className="form-field-name selector" valueKey="value"
labelKey="label" value={cityCode} onChange={this.cityChange} isDisabled={province ? false : true} />
这是“getCity”函数体:
getCity(province) {
const{binCode,username,code} = this.state;
if(!province || province === '' || province === null || province === undefined){
console.log('province:',province);
return {options: [] ,complete:true}; //here throws an error
}
//preparing data
reportService.getCitiesList(data) //make a request to obtain options
.then(res => {
console.log(res);
if (res.success === false && res.message === 'Token is not valid') {
userService.Authorization();
this.getCity();
}
let result = JSON.parse(res.body);
let msg = result.message;
switch (result.Result) {
case "false":
commonHelper.toaster(msg, 'e');
break;
case "true":
//console.log(msg);
let cities = JSON.parse(msg);
const formatted = cities.map((city) => {
return Object.assign({}, {
value: city.geography_id,
label: city.geography_name
});
});
formatted.push({
value: '',
label: 'none'
});
console.log(formatted);
return {options: formatted , complete: true}; //also here throws an error if we get to it
//this.setState({cityOptions:formatted});
break;
};//end of switch
});
};//end of getCity function
所以问题是,将参数传递给 loadOptions 函数会引发此错误“Uncaught TypeError: loadOptions is not a function at Async.loadOptions”,任何人都可以告诉我我有什么选项,而不是传递参数或为什么传递参数导致这个?
最佳答案
React-Select loadOptions
采用一个方法,但在这段代码中,当 prop 需要一个函数时,您实际上将返回值作为 prop 传递:
<AsyncSelect cacheOptions defaultOptions loadOptions={this.getCity(province)}
id="city" className="form-field-name selector" valueKey="value"
labelKey="label" value={cityCode} onChange={this.cityChange} isDisabled={province ? false : true} />
我明白你想要做什么(相关选择),这只是你如何实现它。如果 provinceChange
在组件状态上设置省份,那么 getCity
会执行如下操作:
getCity = inputValue => {
const {province} = this.state;
// go get my city based on province, and filter by inputValue, if not null
};
// ...
<AsyncSelect loadOptions={this.getCity} />
关于javascript - 未捕获的类型错误 : loadOptions is not a function at Async. loadOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54885708/