首页 > 解决方案 > 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

我做错了什么?

标签: javascriptreactjsfrontend

解决方案


在 MainApp 的每次渲染上都会连续执行获取。考虑使用效果来解决这个问题。


推荐阅读