gpt4 book ai didi

javascript - 如何延迟页面渲染直到从 api 收到数据

转载 作者:行者123 更新时间:2023-12-05 02:41:43 24 4
gpt4 key购买 nike

当第一次使用 API 请求加载页面时,它会出错。但是在页面加载后,如果我放回相同的代码,它就可以正常工作。有人可以帮助我在这里缺少什么吗?或者告诉我延迟页面加载直到从 api 加载数据的技巧

import React, { useState, useEffect } from 'react'

export default function ProductPage({ data }) {

const [productData, setProductData] = useState(null)

useEffect(() => {
getProductdata()
}, [])

async function getProductdata(){
const secret = "SECRET"
const request = await fetch(`https://app.myapi.com/api/products/${data.productsCsv.id}`, {
headers: {
'Authorization': `Basic ${btoa(secret)}`,
'Accept': 'application/json'
}
}).then((request => request.json()))
.then(data => setProductData(data))
.catch(err=>console.log(err))
}

console.log("pdata",productData) // returns null on initial load and then it filled with data.


return (
<>
<div className="stock mb-4 ">
<p className="tracking-wider mb-2">Size</p>
{productData.variants.map((variant,index)=>{
<p>{variant.stock}</p>
if(variant.stock != 0){
return (


<button className={`p-2 border-gray-200 border mr-2 mb-2 hover:bg-black hover:text-white cursor-pointer focus:border-black ${activeSize === index ? 'bg-black text-white' : null}`} role="button" tabIndex={0}
onClick={() => {toggleSize(index); setSize(size)}}
onKeyDown={() => {toggleSize(index); setSize(size)}} key={index}>{variant.variation[0].option}-{variant.stock}</button>


)
}
else {
return(
<button className={`p-2 border-gray-200 border mr-2 mb-2 ${variant.stock == 0 ?'bg-gray-400 line-through text-red-500': null}`} disabled role="button" tabIndex={0}
onClick={() => {toggleSize(index); setSize(size)}}
onKeyDown={() => {toggleSize(index); setSize(size)}} key={index}>{variant.variation[0].option}-{variant.stock}</button>
)
}
})}

</div>
</>
)

最佳答案

设置一些状态并返回另一个组件,直到您获得数据,它应该看起来像这样:

import React, { useState, useEffect } from 'react'

export default function ProductPage({ data }) {

const [productData, setProductData] = useState(null)
const [loading, setLoading] = useSate(true) // set some state for loading

useEffect(() => {
getProductdata()
}, [])

async function getProductdata(){
const secret = "SECRET"
const request = await fetch(`https://app.myapi.com/api/products/${data.productsCsv.id}`, {
headers: {
'Authorization': `Basic ${btoa(secret)}`,
'Accept': 'application/json'
}
}).then((request => request.json()))
.then((data) => {
setProductData(data)
setLoading(false) // set Loading to false when you have the data
})
.catch(err=>console.log(err))
}

//use the piece of loading state to return other component until you have the data
if (loading) {
return (<div>Replace me with a loading component...</div>)
}

return (
<>
...
</>
)

关于javascript - 如何延迟页面渲染直到从 api 收到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67979782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com