简体   繁体   English

为什么我在反应钩子中得到这个无限循环

[英]Why am I getting this infinite loop in react hooks

I am fetching from a JS file that mimics an API and has a couple of methods that act as endpoints, I am getting the data when I console log but I can't wrap my head around why I am getting an infinite loop when using hooks.我从一个模仿 API 的 JS 文件中获取,并且有几个充当端点的方法,我在控制台日志时获取数据,但我无法理解为什么在使用钩子时会出现无限循环. Yes, I have searched for similar questions but I still don't understand.是的,我已经搜索过类似的问题,但我仍然不明白。

 import React, { useEffect, useState } from "react"; import { api } from "../api/api.min.js"; // import axios from "axios"; function NonsenseComponent() { const [data, setData] = useState(); console.log(data); // function getItems(items) { // // console.log(items, " items finns"); // setData(items); // } // console.log("darn"); const x = api.XMLHttpRequest(); x.onreadystatechange = function () { if (x.readyState == 4 && x.status == 200) { var item = JSON.parse(this.responseText); var items = []; // init array to store contacts for (var i = 0; i < item.length; i++) { items.push({ date: item[i].date, text: item[i].text, id: item[i].id, }); } // setData(items); } }; x.open("GET", "/getitems", true); x.send(); useEffect(() => { // setData({}); }, []); return ( <div> {/* {data.map((item) => ( <ul key={item[0].id}> <li>{item[0].date}</li> </ul> ))} */} </div> ); } export default NonsenseComponent;

Calling function on component body in React is discouraged (you don't know how many times function will be called).不鼓励在 React 的组件主体上调用 function(你不知道 function 会被调用多少次)。 Lets say you want to fetch data once on component load, you could modify you code like this:假设您想在组件加载时获取一次数据,您可以像这样修改代码:

import React, { useEffect, useState } from "react";
import { api } from "../api/api.min.js";
// import axios from "axios";

function NonsenseComponent() {
  const [data, setData] = useState({}); //<-- default value for data is {}
  console.log(data);

  // function getItems(items) {
  //   // console.log(items, " items finns");
  //   setData(items);
  // }
  // console.log("darn");

  useEffect(() => {
    const x = api.XMLHttpRequest();
    x.onreadystatechange = function () {
    if (x.readyState == 4 && x.status == 200) {
      var item = JSON.parse(this.responseText);
      var items = []; // init array to store contacts
      for (var i = 0; i < item.length; i++) {
        items.push({
          date: item[i].date,
          text: item[i].text,
          id: item[i].id,
        });
      }

      setData(items); // <-- here you can set your state
    }
  };
  x.open("GET", "/getitems", true);
  x.send();
  }, []);

  return (
    <div>
     
      {data.map((item) => (
        <ul key={item[0].id}>
          <li>{item[0].date}</li>
        </ul>
      ))}
    </div>
  );
}

export default NonsenseComponent;

This should solve your problem.这应该可以解决您的问题。

Because everything in your function will run when the component get mount or update.因为 function 中的所有内容都将在组件安装或更新时运行。 Your api part will run everytime the component update but that part also change the state -> the state changed -> component update -> api run -> infinite loop. Your api part will run everytime the component update but that part also change the state -> the state changed -> component update -> api run -> infinite loop.
You should put that api call inside useEffect with an empty dependency.您应该将 api 调用放在 useEffect 中,并带有一个空依赖项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM