我正在使用react select的AsyncSelect组件,并尝试使用以下代码从回调中解决它:
loadOptions(inputValue, callback) {
this.props.asyncFunctionWithCallback(resp => {
callback(resp);
});
}
asyncFunctionWithCallback()
是一个接收回调的异步函数当承诺得到解决时称为
asyncFunctionWithCallback(doneCallback) {
// Call some async code
fetch(url).then(response => {
doneCallback(response)
}
}
我正试图从asyncFunctionWithCallback()
的回调中调用react select的callback()
,但它似乎没有被调用,因为asyncFunctionWithCallback()
永远被重复调用。
我想我没有正确地传递回调,但无法弄清楚我做错了什么。
您需要将res.json值从fetch传递给类似的回调
asyncFunctionWithCallback(doneCallback) {
// Call some async code
fetch(url)..then(res => res.json())then(response => {
doneCallback(response)
}
}
然而,由于您已经有了异步代码,因此最好使用promist方法进行loadOptions
loadOptions(inputValue) {
return this.props.asyncFunctionWithCallback();
}
asyncFunctionWithCallback() {
// Call some async code
return fetch(url)..then(res => res.json());
}