gpt4 book ai didi

javascript - react : async and await not working with fetch

转载 作者:行者123 更新时间:2023-12-05 02:44:26 25 4
gpt4 key购买 nike

我在 Node 服务器上有 API,调用时返回这样的 JSON:

{"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuantity":100}]}

我正在尝试使用带有 React 的获取 API 向用户显示所有这些信息,但无论我的调用返回什么undefined。这是我的 React 代码:

const [products, setProducts] = useState({})

async function getProducts() {
await fetch(`http://127.0.0.1:5000/listProducts`)
.then(response => response.json())
.then(response=>{
setProducts({products:response.result})
console.log(response.result);
products.map(products =>
<h1>{products.ProductName}</h1>
<h1>{products.ProductDescription}</h1>
)
})
.catch(err=>console.error(err))
}

函数 getProducts() 在页面加载时被调用一次。我做错了什么?提前致谢。

最佳答案

试一试它会起作用

const handleFetchData = async () => {
const response = await fetch(`https://api.unsplash.com/photos/random?client_id=${process.env.NEXT_PUBLIC_UNSPLASH_API_ACCESS_KEY}`);
const data = await response.json();
console.log(data);
}

useEffect(() => {
handleFetchData();
},[])

关于javascript - react : async and await not working with fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66507362/

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