简体   繁体   English

不调用 react-select 异步回调

[英]react-select async callback is not called

I'm using react-select's AsyncSelect component, and try to resolve it from a callback with the following code:我正在使用 react-select 的 AsyncSelect 组件,并尝试使用以下代码从回调中解决它

loadOptions(inputValue, callback) {
  this.props.asyncFunctionWithCallback(resp => {
    callback(resp);
  });
}

asyncFunctionWithCallback() is an async function that receives a callback that is called when the promise is resolved: asyncFunctionWithCallback()是一个异步 function 接收在 promise 解决时调用的回调:

asyncFunctionWithCallback(doneCallback) {
  // Call some async code
  fetch(url).then(response => { 
    doneCallback(response) 
  }
}

I'm trying to call react-select's callback() from within asyncFunctionWithCallback() 's callback, but seems like it is not being called, as asyncFunctionWithCallback() is being called repeatedly forever.我试图从asyncFunctionWithCallback()的回调中调用 react-select 的callback() ,但似乎它没有被调用,因为asyncFunctionWithCallback()被永远重复调用。

I guess I'm not passing the callback properly, but cannot figure out what am I doing wrong.我想我没有正确传递回调,但无法弄清楚我做错了什么。

You would need to pass on the res.json value from fetch to the callback like您需要将 res.json 值从 fetch 传递给回调,例如

asyncFunctionWithCallback(doneCallback) {
  // Call some async code
  fetch(url)..then(res => res.json())then(response => { 
    doneCallback(response) 
  }
}

However since you already have an async code its better to use the promist approach for loadOptions但是,由于您已经有了异步代码,因此最好使用 promist 方法进行 loadOptions

loadOptions(inputValue) {
  return this.props.asyncFunctionWithCallback();
}

asyncFunctionWithCallback() {
  // Call some async code
  return fetch(url)..then(res => res.json());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM