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

时间:2020-07-22 07:55:06

标签: reactjs

从一页导航到另一页后,我试图在页面表中添加新行。以下代码导致无限循环。我该如何避免呢?

function createData(videos, status, model, manage, device, favourite) {
  return { videos, status, model, manage, device, favourite };
}
const rows = [
  createData("https://www.youtube.com/watch?v=ug50zmP9I7s", 'Online', 2, 24, 'Cam1', true),
  createData("https://www.youtube.com/watch?v=Bey4XXJAqS8", 'Offline', 2, 37, 'Am2', true),
  createData("https://www.youtube.com/watch?v=Bey4XXJAqS8", 'Online', 2, 24, 'Zam3', false),
  createData("https://www.youtube.com/watch?v=ug50zmP9I7s", 'Offline', 2, 67, 'Dam4', false),
  createData("https://www.youtube.com/watch?v=Bey4XXJAqS8", 'Online', 2, 49, 'Lam5', false),
];
export default function StreamPage(props) {   
  const [Results, setResults] = React.useState(rows);
  let youtubeURL = props.location.deviceRow;
  if (youtubeURL != null && youtubeURL != "") {
    const newRows = [...rows];
    const newData = createData(youtubeURL, 'Online', 4, 49, 'Lam6', false)     
    setResults(newRows.concat(newData))  //   Here I have infinite loop and error 
  }

  return ()
};

setResults()被多次调用,结果存在一个循环

2 个答案:

答案 0 :(得分:0)

您必须使用useEffect来避免无限循环:

// ...

React.useEffect(() => {
  if (youtubeURL != null && youtubeURL != "") {
    const newData = createData(youtubeURL, 'Online', 4, 49, 'Lam6', false)     
    setResults(prevRows => [...prevRows, newData])
  }
},[youtubeURL])

// ...

答案 1 :(得分:-1)

这是对我有用的修复程序。

 setResults({ Results: Results.push(newData) })