我有一个简单的程序,它从节点后端接收一些 JSON 数据并将接收到的数据设置为状态。问题是它无限次重置状态,从而创建无限渲染。
这是 JSON 数据
[
{
"id": 1,
"name": "Product 1",
"category": "C1",
"price": "100"
},
{
"id": 2,
"name": "Product 2",
"category": "C1",
"price": "80"
},
{
"id": 3,
"name": "Product 3",
"category": "C3",
"price": "120"
}
]
Run Code Online (Sandbox Code Playgroud)
这是反应程序。
import React, { useState } from 'react'
const MainApp = () => {
const [products, setProducts] = useState([])
fetch("http://localhost:5000/products")
.then((res) => res.json())
.then((res) => {setProducts(res)})
.catch((err) => console.error(err))
console.log("Products:",products) //This keep getting logged forever.
return (
<h1>Test</h1>
) …Run Code Online (Sandbox Code Playgroud)