在反应选择异步上出现网络错误和空下拉列表



我正在尝试在我的 React 应用程序上实现 react-select。我的 API 端点使用简单的 get 请求,我确信它会发送响应,例如:

[
{
value: 123,
label: "Michael Carrick",
first_name: "Michael",
last_name: "Carrick",
country: "England",
first_nationality: "England",
team_id: 134,
Team.name: "Manchester United"
},
{
value: 234,
label: "Jack Clarke",
first_name: "Jack",
last_name: "Clarke",
country: "England",
first_nationality: null,
team_id: 254,
Team.name: "Leeds United"
}
]

在我的组件中,我有以下部分:

const promiseOptions = (inputValue) => {
axios.get('URL?q=' + inputValue)
.then(res => {
const data = res.data;
return data;
})
.catch((error) => {
console.log(error);
});
}
export default class extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
inputValue: ''
};
}
componentDidMount() {
axios.get('URL')
.then(res => {
const data = res.data;
this.setState({ data });
return data;
})
.catch((error) => {
console.log(error);
});
}
handleInputChange (newValue) => {
this.setState({ inputValue });
return inputValue;
};
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
)
}
}

当我加载页面时,我单击下拉选择框,但它显示"无选项"。当我在框中键入内容时,我可以看到我键入的内容,但在控制台上,每次输入更改时都会出错:

VM6467:1 GET ENDPOINT-URL?q=c 0 ()
(anonymous) @ VM6467:1
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:51
Axios.(anonymous function) @ Axios.js:61
wrap @ bind.js:9
promiseOptions @ select.js:14
loadOptions @ Async.js:167
(anonymous) @ Async.js:88
callCallback @ react-dom.development.js:10764
commitUpdateQueue @ react-dom.development.js:10797
commitLifeCycles @ react-dom.development.js:14264
commitAllLifeCycles @ react-dom.development.js:15342
callCallback @ react-dom.development.js:100
invokeGuardedCallbackDev @ react-dom.development.js:138
invokeGuardedCallback @ react-dom.development.js:187
commitRoot @ react-dom.development.js:15481
completeRoot @ react-dom.development.js:16496
performWorkOnRoot @ react-dom.development.js:16440
performWork @ react-dom.development.js:16358
flushInteractiveUpdates$1 @ react-dom.development.js:16605
batchedUpdates @ react-dom.development.js:2143
dispatchEvent @ react-dom.development.js:4551
interactiveUpdates$1 @ react-dom.development.js:16592
interactiveUpdates @ react-dom.development.js:2150
dispatchInteractiveEvent @ react-dom.development.js:4528
select.js:20 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)

我试图尽可能多地遵循示例示例,但似乎无法使其工作。

编辑:在我的快速应用程序上允许 CORS。

尝试使用此代码,您需要使用回调:

const promiseOptions = (inputValue, callback) => { //add callback param axios.get('URL?q=' + inputValue) .then(res => { const data = res.data; callback(data); //<= using callback }) .catch((error) => { console.log(error); }); }

最新更新