reactjs - 从 API 获取 React 下拉列表
问题描述
我想构建“React Dropdown”,当我输入他名字的第一个字母时,它会给我选择用户的选项。
用户数据来自我的 JSON 格式的后端 API。
// http://localhost:5000/users
{
"users": [
{
"company_id": 1,
"name": "Sally Mae"
},
{
"company_id": 2,
"name": "Johnathan Ives"
},
{
"company_id": 3,
"name": "John Smith"
}
]
}
这是我的获取部分,但我无法获取,但我的服务器正在运行,这是代码
fetchData = (inputValue, callback) => {
if (!inputValue) {
callback([]);
} else {
setTimeout(() => {
fetch("http://127.0.0.1:5000/users/" + inputValue, {
method: "GET",
})
.then((resp) => {
console.log(resp);
return resp.json()
})
.then((data) => {
const tempArray = [];
data.forEach((users) => {
console.log(tempArray);
tempArray.push({ label: `${users.name}`, value: `${users.name}`});
console.log(tempArray);
});
callback(tempArray);
})
.catch((error) => {
console.log(error, "catch the hoop")
});
});
}
}
感谢任何帮助!
解决方案
我认为你在这里误解的是callback
,你的loadOptions
道具是你包装检索方法的地方。
const getData = (inputValue) =>
fetch('http://127.0.0.1:5000/users/' + inputValue, {
method: 'GET',
})
.then((resp) => resp.json())
.then((data) =>
data.map((user) => ({ label: user.name, value: user.name }))
)
.catch((error) => {
console.log(error, 'catch the hoop');
});
const fetchData = (inputValue, callback) => {
if (!inputValue) {
callback(Promise.resolve([]));
} else {
callback(getData(inputValue));
}
};