简体   繁体   English

React UseEffect 渲染无限循环

[英]React UseEffect render infinite loop

I seem to have an infinite loop in my code but I can't seem to see where, I usually see this if I am setting the state of something that is a dependency of useEffect but here the two variables (values / items) are completely seperate.我的代码中似乎有一个无限循环,但我似乎看不到在哪里,如果我设置 state 的东西是 useEffect 的依赖项但这里两个变量(值/项)完全是分开。

App.js应用程序.js

import React from 'react';
import './style.css';
import MyComponent from './MyComponent.js';

export default function App() {
  return (
    <div>
      <MyComponent />
    </div>
  );
}

MyComponent.js我的组件.js

import React, { useEffect, useState } from 'react';

const MyComponent = ({ values = [] }) => {

  console.log('MyComponent Reloaded');
  const [items, setItems] = useState();

  useEffect(() => {
    const loadItems = () => {
      //setItems([]);   //why does this cause infinite render loop?
    };

    loadItems();
  }, [values]);

  return <></>;
};

export default MyComponent;

Why does this cause a render loop?为什么这会导致渲染循环?

I have an example build Here (Uncomment the commented line to begin render loop)在这里有一个示例构建(取消注释注释行以开始渲染循环)

You need to introduce the default values of the props the right way:您需要以正确的方式引入道具的默认值:

import React, { useEffect, useState } from 'react';

const MyComponent = ({ values }) => {
  console.log('MyComponent Reloaded');
  const [items, setItems] = useState();

  useEffect(() => {
    console.log(values)
    const loadItems = () => {
      setItems([]);
    };

    loadItems();
  }, [values]);

  return <></>;
};

MyComponent.defaultProps = {
  values: []
}

export default MyComponent;

There are two possible bugs in the code:代码中有两个可能的错误:

  • According to your code, values variable is created every time, when checked with the previous values variable it is not same.根据您的代码,每次都会创建values变量,当与以前的values变量检查时,它是不一样的。 So it causes infinite loop.所以它会导致无限循环。

    • To fix this use default props.要解决此问题,请使用默认道具。

       const MyComponent = ({ values }) => {... MyComponent.defaultProps = { values: [] }
  • As in your question,this line causes you the infinite loop正如你的问题,这条线会导致你无限循环

     //setItems([]);
    • To overcome this为了克服这个

      Add items dependency along with values , so that both values are watched before re-rendering.添加items依赖项以及values ,以便在重新渲染之前监视两个值。

       useEffect(() => { console.log(values) const loadItems = () => { setItems([]); }; loadItems(); }, [values,items]);

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

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