简体   繁体   English

使用 Axios 和 useState/useEffect 无限重新渲染 React 功能组件?

[英]Infinite Re-rendering of React Functional Component using Axios and useState/useEffect?

I am trying to create a React Functional Component using Typescript that will get data from an API and then send that data to another component, however, I am getting an error of "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."我正在尝试使用 Typescript 创建一个 React 功能组件,它将从 API 获取数据,然后将该数据发送到另一个组件,但是,我收到错误消息“错误:重新渲染次数过多。React 限制了渲染次数以防止无限循环。”

Please offer any advice!请提供任何建议!

useEffect(() => {
    await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random').then((resp) => {
            setQuote1(resp.data.data[0]);
        });
    getQuote();
}, []);

Snippet of Code Causing Error导致错误的代码片段

EDIT: Here is the entire File where the error is occurring.编辑:这是发生错误的整个文件。

import React, { useEffect, useState } from 'react';
import { Row, Col, CardGroup } from 'reactstrap';
import axios from 'axios';

import QuoteCard from './QuoteCard';

const MainQuotes = () => {
    const [quote1, setQuote1] = useState();

    useEffect(() => {
        await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random').then((resp) => {
                setQuote1(resp.data.data[0]);
            });
        getQuote();
    }, []);

    return (
        <Row>
            <Col>
                <CardGroup>
                    <QuoteCard quoteData={quote1} />
                </CardGroup>
            </Col>
        </Row>
    );
};

export default MainQuotes;

Depending on the type of quote1 (I'm assuming it's a string) update to:根据 quote1 的类型(我假设它是一个字符串)更新为:

const [quote1, setQuote1] = useState('')

useEffect(() => {
  function fetchQuote() {
    await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random')
    .then((resp) => {
      setQuote1(resp.data.data[0]);
    });
  }  
  if (!quote1) {
    fetchQuote();
  }
}, []);

Because the response from the API is a random quote, you have to handle it based on the value of quote1.因为API的response是随机报价,所以要根据quote1的值来处理。 This should work because quote1 will only be updated after the component mounts (when the value is an empty string), and the following render won't update state, so useEffect won't loop infinitely.这应该可以工作,因为 quote1 只会在组件安装后更新(当值为空字符串时),并且以下渲染不会更新 state,因此useEffect不会无限循环。

Before the edit, I assumed the axios request was inside of the getQuote function. I have updated my answer to reflect the code you have posted.在编辑之前,我假设 axios 请求在 getQuote function 的内部。我更新了我的答案以反映您发布的代码。

If the API response was static, because the items in the dependency array only cause a re-render if they are changed from their current value, it only causes a re render immediately after the first state update.如果 API 响应是 static,因为依赖项数组中的项目只有在它们的当前值发生变化时才会导致重新渲染,所以它只会在第一次 state 更新后立即导致重新渲染。

Can we get your entire code please?我们可以得到你的完整代码吗? It seems the problem is going to be with your state hook and figuring out exactly what its doing.看来问题出在您的 state 挂钩上,并弄清楚它到底在做什么。

My guess as of now is your state hook "setQuote1" is being invoked in a way that causes a re-render, which then would invoke your useEffect() again (as useEffect runs at the end of the render cycle) and thus, calling upon your setQuote1 hook again.我现在的猜测是你的 state 挂钩“setQuote1”正在以导致重新渲染的方式被调用,然后会再次调用你的 useEffect() (因为 useEffect 在渲染周期结束时运行)因此,调用再次在您的 setQuote1 挂钩上。 This repeats itself indefinitely.这无限期地重复。

useEffect() allows for dependencies and gives you the power to tell exactly when useEffect() should be invoked. useEffect() 允许依赖关系,并让您能够准确判断何时应调用 useEffect()。

Example: useEffect(() { code here }, [WATCH SPECIFICALLY THIS AND RUN ONLY WHEN THIS UPDATES]).示例:useEffect(() { code here }, [特别注意这个并且仅在更新时运行])。

When you leave the dependency array empty, you tell the hook to run whenever ANYTHING updates state. This isn't necessarily bad but in some cases you only want your useEffect() to run when a specific state updates.当您将依赖项数组留空时,您告诉挂钩在任何更新 state 时运行。这不一定是坏事,但在某些情况下,您只希望 useEffect() 在特定 state 更新时运行。

Something in your application must be triggering your useEffect() hook to run when you aren't wanting it to.您的应用程序中的某些东西必须在您不希望它运行时触发您的 useEffect() 挂钩运行。

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

相关问题 在 useCallback 挂钩中使用 Axios 时反应功能组件无限重新渲染? - React functional component re-rendering infinitely when using Axios in useCallback hook? 组件不会使用“useEffect”钩子在 React 中重新渲染 - Component not re-rendering in React using a 'useEffect' hook React hook form useEffect 不会通过调用另一个组件来重新渲染功能组件 - React hook form useEffect not re-rendering functional component with call to another component 避免在反应组件中无限重新渲染 - Avoiding infinite re-rendering in react component 如何防止在 React 中使用 useEffect() 无限重新渲染? - How to prevent infinite re-rendering with useEffect() in React? 更改 UseState Hook React 组件后不会重新渲染 - After changing a UseState Hook React component is not re-rendering 更改 UseState Hook React 组件后不重新渲染 - After changing UseState Hook React component not re-rendering 如何防止在 React 中的功能组件中重新渲染 - How to prevent re-rendering in functional component in React 在 React 功能组件中重新渲染 - 为什么会出现这种行为? - Re-rendering in React functional component - why this behavior? React.map 不在 state 上重新渲染功能组件的变化 - React .map not re-rendering on state change in functional component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM