Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

reactjs - Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

After navigation from one page to another page, I am trying to add a new row to the table of the page. The below code results in an infinite loop. How can I avoid it?

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() is called multiple times and as a result there is a loop

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've to use useEffect to avoid infinite loop:

// ...

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

// ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...