[英]How do I style the output from this async await function that successfully fetches data from a database?
[英]How do I get data from the async/await function before rendering out the UI?
我正在研究 Github API 并使用异步/等待 function 来获取用户存储库的列表。
我面临的问题是,我正在使用一个Dropdown component
,我必须在其中提供一个充满 repo 列表的数组,该数组将作为下拉列表工作,并且该数组数据来自 async/await function。
const list = []
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => list.push(details.data[0].name))
console.log('List Array', list)
console.log([...list])
}
因此,UI 在 function 执行之前呈现,并且items array
变为空。
<>
<DropDown items={[...list]} placeholder='Select a Repository' />
</>
我正在使用spread operator
在我的Dropdown component
中获取数据
我如何确保我确实从异步等待 function 获取项目道具中的数据,我相信 function 也不能同步,因为它正在处理 ZDB974238714CA8ADE634A7CE1D08 请求。 什么是解决这个问题的好策略?
非常感谢任何帮助。
谢谢你
您可以使用虚假值初始化列表数据,例如 null 并使用三元运算符停止下拉 UI 呈现,直到您的 API 调用完成执行并使用数组填充列表数据。 这将是“真实”值,然后可以呈现您的下拉菜单。
如果您使用基于钩子的组件,则必须使用useState
和useEffect
来实现此目的。 它看起来像这样
const [list, setList] = useState([]);
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => {
setList((prevState) => {
prevState.push(details.data[0].name);
return prevState;
});
});
console.log('List Array', list);
console.log([...list]);
}
useEffect(() => {
(async () => {
await fetchRepos();
})();
}, []);
可以试试下面的解决方案
const [isShowDropdown, setDropdown] = useState(false);
const list = []
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => list.push(details.data[0].name))
setDropdown(true)
console.log('List Array', list)
console.log([...list])
}
像这样渲染下拉菜单
<>
{isShowDropdown?<DropDown items={[...list] || [] } placeholder='Select a Repository' />:null}
</>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.