React函数不断刷新页面导致巨大的内存泄漏

Cou*_*age 2 express reactjs

我正在用 React 构建一个网站。目前,我已经创建了渲染元素的函数,并对我在 Node.js 中创建的 API 进行 PUT fetch 调用。它是这样的:

import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import Alert from "../elements/Alert";
import Axios from "axios";

export default function UpdateCourse() {
  const id = window.location.href.split("?")[1];
  console.log(id);

  const [dishName, setdishName] = useState("");
  const [category, setcategory] = useState("");
  const [author, setauthor] = useState("");
  const [ingredients, setingredients] = useState([]);
  const [cookingTime, setcookingTime] = useState("");
  const [sourceUrl, setsourceUrl] = useState("");
  const [imageUrl, setimageUrl] = useState("");
  const [isPublished, setisPublished] = useState("true");
  const [price, setprice] = useState("");
  const [tags, settags] = useState([]);
  const [alert, setAlert] = useState("");
  const history = useHistory();

  const url = `http://localhost:1234/api/courses/find/${id}`;

  useEffect(async () => {
    const result = await Axios.get(url);
    setdishName(result.data.dishName);
    setcategory(result.data.category);
    setauthor(result.data.author);
    setingredients(result.data.ingredients);
    setcookingTime(result.data.cookingTime);
    setsourceUrl(result.data.sourceUrl);
    setimageUrl(result.data.imageUrl);
    setisPublished(result.data.isPublished);
    setprice(result.data.price);
    settags(result.data.tags);
    console.log(`Nie powinno`);
  });

  async function update() {
    let item = {
      dishName,
      category,
      author,
      ingredients,
      cookingTime,
      sourceUrl,
      imageUrl,
      isPublished,
      price,
      tags,
    };

    console.log(item);
    console.log(JSON.stringify(item));

    const result = await fetch(`http://localhost:1234/api/courses/${id}`, {
      method: "PUT",
      body: JSON.stringify(item),
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    console.log(result);
    if (result.status !== 200) {
      return setAlert(result.status + " " + result.statusText);
    }

    history.push("/");
    window.location.reload();
  }

  const handleIngredientsChange = (event, index) => {
    console.log("id: " + event.target.id + "\nvalue: " + event.target.value);
    const shallowCopy = [...ingredients];

    shallowCopy[index] = {
      ...shallowCopy[index],
      [event.target.id]: event.target.value,
    };

    setingredients(shallowCopy);
  };

  return (
    <div>
      {alert !== "" && <Alert alert={alert}></Alert>}
      <div>
        <p>Dishname</p>
        <input
          autoFocus="autofocus"
          required="required"
          type="text"
          className="form-control"
          placeholder={dishName}
          onChange={e => setdishName(e.target.value)}
        />
      </div>
      <br />

      <div>
        <p>Category</p>
        <input
          required="required"
          type="text"
          className="form-control"
          placeholder={category}
          onChange={e => setcategory(e.target.value)}
        />
      </div>
      <br />

      <div>
        <p>Author</p>
        <input
          type="text"
          onChange={e => setauthor(e.target.value)}
          className="form-control"
          required="required"
          placeholder={author}
        />
      </div>
      <br />

      <p>Ingredients</p>
      {ingredients.map(({ quantity, unit, description }, index) => {
        console.log("tick");
        return (
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <h5>Quantity </h5>
            <br />
            <input
              id="quantity"
              type="text"
              onChange={event => handleIngredientsChange(event, index)}
              className="form-control"
              required="required"
              placeholder={quantity}
            />
            <h5> Unit </h5>
            <div>
              <input
                id="unit"
                type="text"
                onChange={event => handleIngredientsChange(event, index)}
                className="form-control"
                required="required"
                placeholder={unit}
              />
            </div>
            <h5> Description </h5>

            <input
              id="description"
              type="text"
              onChange={event => handleIngredientsChange(event, index)}
              className="form-control"
              required="required"
              placeholder={description}
            />
          </div>
        );
      })}

      <br />
      <div>
        <p>Cooking time</p>
        <input
          type="text"
          onChange={e => setcookingTime(e.target.value)}
          className="form-control"
          required="required"
          placeholder={cookingTime}
        />
      </div>
      <br />

      <div>
        <p>Source url</p>
        <input
          type="text"
          onChange={e => setsourceUrl(e.target.value)}
          className="form-control"
          required="required"
          placeholder={sourceUrl}
        />
      </div>
      <br />

      <div>
        <p>Image url</p>
        <input
          type="text"
          onChange={e => setimageUrl(e.target.value)}
          className="form-control"
          required="required"
          placeholder={imageUrl}
        />
      </div>
      <br />

      <div>
        <p>Published</p>
        <input
          type="text"
          onChange={e => setisPublished(e.target.value)}
          className="form-control"
          required="required"
          placeholder={"default: true"}
        />
      </div>
      <br />

      <div>
        <p>Price</p>
        <input
          type="text"
          onChange={e => setprice(e.target.value)}
          className="form-control"
          required="required"
          placeholder={price}
        />
      </div>
      <br />

      <div>
        <p>Tags</p>
        <input
          type="text"
          onChange={e => settags(e.target.value)}
          className="form-control"
          required="required"
          placeholder={tags}
        />
      </div>
      <br />

      <button onClick={update}>Submit</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

然而,当页面确实加载并且几秒钟后一切看起来都正确时,我的计算机开始发出很大的噪音,当我执行 console.log 来检查它在做什么时,我得到这个: https ://i.stack.imgur.com/5Sg3q .png

你能告诉我我做错了什么吗?我确实根据我读到的有关此问题的内容使用了 useEffect 函数。可悲的是我所做的一切都没有解决我的问题。

编辑:这是 JSON 对象在 MongoDB 中的样子:

{
    "isPublished": true,
    "tags": [
        "pizza"
    ],
    "_id": "60ae108ddfb18463c046a5ba",
    "dishName": "Pizza with Cauliflower Crust",
    "category": "pizza",
    "ingredients": [
        {
            "_id": "60a4cfa48c20aa5c18517606",
            "quantity": 1,
            "unit": "",
            "description": "medium head cauliflower cut into florets"
        },
        {
            "_id": "60a4cfa48c20aa5c18517607",
            "quantity": 1,
            "unit": "",
            "description": "egg"
        },
        {
            "_id": "60a4cfa48c20aa5c18517608",
            "quantity": 0.5,
            "unit": "cup",
            "description": "mozzarella shredded"
        },
        {
            "_id": "60a4cfa48c20aa5c18517609",
            "quantity": 1,
            "unit": "tsp",
            "description": "oregano or italian seasoning blend"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760a",
            "quantity": null,
            "unit": "",
            "description": "Salt and pepper to taste"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760b",
            "quantity": 1,
            "unit": "cup",
            "description": "chicken cooked and shredded"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760c",
            "quantity": 0.5,
            "unit": "cup",
            "description": "barbecue sauce"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760d",
            "quantity": 0.75,
            "unit": "cup",
            "description": "mozzarella shredded"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760e",
            "quantity": null,
            "unit": "",
            "description": "Red onion to taste thinly sliced"
        },
        {
            "_id": "60a4cfa48c20aa5c1851760f",
            "quantity": null,
            "unit": "",
            "description": "Fresh cilantro to taste"
        }
    ],
    "cookingTime": 60,
    "sourceUrl": "https://www.closetcooking.com/cauliflower-pizza-crust-with-bbq/",
    "imageUrl": "https://www.closetcooking.com/wp-content/uploads/2013/02/BBQ-Chicken-Pizza-with-Cauliflower-Crust-500-4699.jpg",
    "price": 29.99,
    "date": "2021-05-26T09:10:37.620Z",
    "__v": 0
}
Run Code Online (Sandbox Code Playgroud)

Que*_*sel 5

在 useEffect 中设置不具有空依赖项数组的状态将导致循环。您应该在 useEffect 中添加一个空数组,它基本上充当前一个数组componentDidMount(),因此只会触发一次。

 useEffect(async () => {
    const result = await Axios.get(url);
    setdishName(result.data.dishName);
    setcategory(result.data.category);
    setauthor(result.data.author);
    setingredients(result.data.ingredients);
    setcookingTime(result.data.cookingTime);
    setsourceUrl(result.data.sourceUrl);
    setimageUrl(result.data.imageUrl);
    setisPublished(result.data.isPublished);
    setprice(result.data.price);
    settags(result.data.tags);
    console.log(`Nie powinno`);
  }, []); <=== Here
Run Code Online (Sandbox Code Playgroud)