Q
Q
Quintis2019-12-11 23:59:43
JavaScript
Quintis, 2019-12-11 23:59:43

Why does an infinite loop appear and how to avoid it?

Good day, I want to write a simple paginator in React, but when I run the paginatorPage function to load the first page with the eForInit parameter, I get an error due to an infinite loop. How to solve the problem?

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

export default function Paginator({obj}) {
    let [itemsPerButton]  = useState(10)
    let [startIndex , setStartIndex] = useState(0)
    let [finishIndex, setFinishIndex]  = useState(10)
    let [arrItems , setArrItems] = useState([])
    let arrButtons = []
    let arrList = []
    

    const paginatorPage=(e)=> {
        console.log(e)
        e.target.className="active"
        let basicNum = e.target.value;
        setFinishIndex(finishIndex=basicNum*10)
        arrList =[]
        for (  setStartIndex(startIndex=basicNum*10-10) ;startIndex < finishIndex && startIndex <= obj.length-1 ; startIndex++) {
            arrList.push(<p key={obj[startIndex].title}>{obj[startIndex].title}</p>)
        }
        setArrItems(arrItems=[...arrList])
    }
    let eForInit = {
        target:{
            value:1,
            className:''
        }
    }
        paginatorPage(eForInit)



    let buttons = Math.ceil(obj.length/itemsPerButton);
  
    for (let index = 1; index <= buttons; index++) {
        arrButtons.push(
    <button value={index} key={index} onClick={(e)=>{paginatorPage(e)}}>{index}</button>
    )}
  

    return (
        <>
        <div>
            i am Paginator , data length is {obj.length}
        </div>
        {arrItems}
        <div>
        {arrButtons}
        </div>
        </>
    )
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2019-12-12
@Quintis

Your paginatorPage is called inside the renderer, and it changes the state, which causes a rerender, and paginatorPage is called in the renderer, and so on forever.
Addition:
1) paginatorPage must be either a function or a function handler, but not both at the same time as you have, which is why you have to hack with the creation of a fake event.
2) You have setState in the description of the for loop for some reason.
3) Do not use an array index as a key.
4) This line is redundant
You can just write
and wrap paginatorPage in useCallback.
5) I didn’t understand what is happening here,
but I understood exactly what is happening is not at all what you expect from it.
6) Where is the setter for? 7) Semicolons, you don't have them, always put them.
8) You can't write like this Firstly, finishIndex is a state, it needs to be changed only through the corresponding set* function, the code becomes incomprehensible and confusing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question