【发布时间】:2021-06-05 00:12:34
【问题描述】:
我在节点服务器上有 API 在调用时返回这样的 JSON:
{"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuantity":100}]}
我正在尝试使用带有 React 的 fetch API 向用户显示所有这些信息,但无论我的调用返回什么 undefined。这是我的反应代码:
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() 在页面加载时调用一次。我做错了什么?提前致谢。
【问题讨论】:
-
1.你需要
return await fetch()2。getProducts仍然会产生一个承诺,所以你需要这样消费它。await它或使用getProducts().then() -
如果
async/await只是fetch调用的包装器,也绝对不需要。function getProducts() { return fetch(...); } -
把它包装在 useEffect 中,不要忘记添加任何依赖项。另外,我认为您不应该将 .then 与 async/await 一起使用,如发布的答案中所述。使用其中之一。
-
好吧,现在 JSON 已成功打印到控制台,但我收到错误“无法读取未定义的属性映射”。尝试不使用地图方法显示可能会更好?
-
看起来您在设置状态后直接映射产品。在设置状态之前,产品将是未定义的。在期望他们在那里之前,您需要检查一下。或者,使用 useEffect。请参阅下面的示例
标签: javascript json reactjs fetch-api