【发布时间】:2021-06-06 08:13:39
【问题描述】:
所以我试图将一个 JSON 对象设置为一个状态,但它不断地给出一个空对象。不知道为什么。
import React, {useState} from 'react'
const MainApp = () => {
const [products, setProducts] = useState({})
const url = "http://localhost:5000/products"
fetch(url)
.then(res => res.json())
.then(res => setProducts(res))
.catch(err => { console.log(err) })
console.log(products) //this gives an empty object
}
export default MainApp
这是 http://localhost:5000/products 中的输出
[
{
"id": "trYl7JYATH0",
"description": "Test caption",
"imgThumb": "test.jpg",
"img": "test.jpg",
"link": "test.jpg",
"userId": "X0ygkSu4Sxo",
"userName": "user",
"userLink": "https://unsplash.com/@user",
"tags": [
"building",
"architecture",
"corner",
"black",
"dark",
"balcony",
"night"
]
}
]
【问题讨论】:
-
res.json() 返回什么?
-
fetch(url)是异步的。您开始获取,但是当您的状态仍然为空时,您的程序继续执行下一条语句console.log()。您可以谷歌 async/await fetch 进一步阅读
标签: javascript node.js json reactjs