简体   繁体   中英

React.js “Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.”

So I'm working on learning full stack using React.js with a friend. He's been helping me a ton but unfortunately, isn't available for the next few days so I thought I'd ask here. I know this issue has to deal with the way my useState([]) is set up or something along those lines. Any advice would be great.

import "./App.css";
import AddTodoButton from "./components/AddTodoButton/AddTodoButton";
import { Draggable, Droppable } from 'react-drag-and-drop';
import Todo from "./components/Todo/Todo";

function App() {
  const [todoTodos, setTodoTodos] = useState([]);
  const [inProgressTodos, setInProgressTodos] = useState([]);
  const [doneTodos, setDoneTodos] = useState([]);
  const handleAddTodo = (newTodoToAdd) => {
    setTodoTodos([...todoTodos, newTodoToAdd]);
  };

  const setStateInProgress = (todo) => {
    setInProgressTodos([...inProgressTodos, todo]);
  }

  return (
    <>
      <div className="swimlane-container">
        <Droppable><Swimlane title="Todo" todos={todoTodos} /></Droppable>
        <Droppable types={['todo']} onDrop={setStateInProgress()}><Swimlane title="In progress" todos={inProgressTodos} /></Droppable>
        <Droppable><Swimlane title="Done" todos={doneTodos} /></Droppable>
      </div>
      <div>
        <AddTodoButton onAddTodo={handleAddTodo} />
      </div>
    </>
  );
  
}

export default App;```

The issue is because of calling setStateInProgress() on onDrop event. Instead you should just send the function reference.

Because when you do setStateInProgress() this function gets called during render, and in this function state is getting updated which will trigger a re-render. So this will be a cycle and hence the error.

Make the changes like below

<Droppable types={['todo']} onDrop={setStateInProgress}><Swimlane title="In progress" todos={inProgressTodos} /></Droppable>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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