javascript - React 简单的 fetch 程序运行到一个无限循环
问题描述
我有一个简单的程序,它从节点后端接收一些 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"
}
]
这是反应程序。
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>
)
}
export default MainApp
我做错了什么?
解决方案
在 MainApp 的每次渲染上都会连续执行获取。考虑使用效果来解决这个问题。
推荐阅读
- vba - 当用户在子表单中选择一行时是否存在 On Click 事件?
- wordpress - 使用 WPGraphQL 插件将数据拉入 Gatsby 站点
- python - 我有一个具有 2263 投影的 json 文件,我想使用 pyproj 将其更改为 4326?
- symfony - 如何从 api 平台返回自定义数据?
- powershell - 如何修复:启动存储在变量中的服务
- java - 执行 Java AnnotationProcessor 时出现 ClassNotFound 异常
- python - 如何获取用户输入来创建类的另一个实例?(即从用户规范中添加员工?)
- django - 带有从和到日期的Django范围数据
- php - php - header() 在必须从超过 2 个嵌套文件夹重定向到页面时不起作用
- c# - WebAPI 未在 Asp.net mvc 中返回带有状态码的错误消息