【问题标题】:How to properly avoid error "Too many re-renders in reactjs"如何正确避免错误“reactjs 中的重新渲染过多”
【发布时间】:2020-06-27 20:34:21
【问题描述】:

我使用下面的代码成功显示了 两个 表中的记录,并且工作正常

这是我的问题:

现在我需要在加载记录时显示和隐藏加载图像或文本。我加了

 const [loading, setLoading] = useState(true);
 setLoading(false);

  
let image_loading;
if (loading) {
image_loading = 'Data is being loaded'
} 

在返回中我添加了下面的代码

<span>{image_loading}</span>

当我现在运行脚本时,它显示错误:

错误:重新渲染过多。 React 限制渲染次数以防止无限循环。

似乎导致此错误的代码行是setLoading(false);。我有a reference solution,但它与点击事件有关。

代码如下:

import {initializeBlock, useBase, base, useRecords} from '@airtable/blocks/ui';
import React, { Component } from "react";
import ReactDOM from 'react-dom';



 function Rec() {
  const [loading, setLoading] = useState(true);
  const currentDate = new Date();

const base = useBase();

// get content of first table
 const tab1 = base.getTableByNameIfExists('myfirst_table');
 // grab all the records from that table
 const records = useRecords(tab1);

// get content of second table
const tab2 = base.getTableByNameIfExists('mysecond_table');
 // grab all the records from that table
 const records2 = useRecords(tab2);

if(records2){
setLoading(false);

}

let image_loading;
if (loading) {
image_loading = 'Data is being loaded'
} 

     return (
<div>
    <span>{image_loading}</span>


<div>
<h1> First Records</h1>
             {records.map(record => {

                 return <li key={record.id}>{record.id} </li>


             })}
</div>


<div>
<h1> First Records</h1>
{records2.map(record2 => {

                 return <li key={record2.id}>{record2.id} </li>


             })}

 </div>

 </div>

     );
 }
  
export default Rec;

【问题讨论】:

  • 您正在通过在组件主体中调用 setLoading(false); 创建无限渲染循环 - 将所有内容移到 useEffect() 中

标签: reactjs


【解决方案1】:

通常,您希望在 useEffect 内调用 setState 或 useState 函数,并带有一个条件。问题就在这里:

if (records2) {
  setLoading(false);
}

当代码到达这里时,records2 确实存在,因此它设置了状态。一旦状态发生变化,组件就会重新渲染,并且这个函数会再次运行,并且它会无限循环。

您可以使用useEffect 使setLoading 的运行以其他一些变量为条件。像这样:

useEffect(() => {
  if (records2){
    setLoading(false)
  }
}, [records2])

所以现在setLoading 只会在records2 发生变化并且存在时运行。

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 2022-01-25
    • 2020-12-21
    • 2019-11-21
    • 2022-11-25
    • 2018-12-16
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多