program tip

ReactJS : 최대 업데이트 깊이 초과 오류

radiobox 2020. 8. 9. 10:18
반응형

ReactJS : 최대 업데이트 깊이 초과 오류


ReactJS에서 구성 요소의 상태를 전환하려고하는데 다음과 같은 오류가 발생합니다.

최대 업데이트 수준을 초과했습니다. 이는 구성 요소가 componentWillUpdate 또는 componentDidUpdate 내에서 setState를 반복적으로 호출 할 때 발생할 수 있습니다. React는 무한 루프를 방지하기 위해 중첩 업데이트 수를 제한합니다.

내 코드에서 무한 루프가 보이지 않습니다. 누구든지 도울 수 있습니까?

ReactJS 구성 요소 코드 :

import React, { Component } from 'react';
import styled from 'styled-components';

class Item extends React.Component {
    constructor(props) {
        super(props);     
        this.toggle= this.toggle.bind(this);
        this.state = {
            details: false
        } 
    }  
    toggle(){
        const currentState = this.state.details;
        this.setState({ details: !currentState }); 
    }

    render() {
        return (
            <tr className="Item"> 
                <td>{this.props.config.server}</td>      
                <td>{this.props.config.verbose}</td> 
                <td>{this.props.config.type}</td>
                <td className={this.state.details ? "visible" : "hidden"}>PLACEHOLDER MORE INFO</td>
                {<td><span onClick={this.toggle()}>Details</span></td>}
            </tr>
    )}
}

export default Item;

렌더링 메서드 내에서 toggle을 호출하기 때문에 다시 렌더링되고 toggle이 다시 호출되고 다시 렌더링됩니다.

이 줄은 코드에서

{<td><span onClick={this.toggle()}>Details</span></td>}

당신은 그것을 호출하지 않는 것을 onClick언급 해야 this.toggle합니다

이 문제 해결 하려면

{<td><span onClick={this.toggle}>Details</span></td>}

함수를 호출 할 때 이벤트 객체를 전달해야합니다.

{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}

onClick 이벤트를 처리 할 필요가없는 경우 다음을 입력 할 수도 있습니다.

{<td><span onClick={(e) => this.toggle()}>Details</span></td>}

이제 함수 내에 매개 변수를 추가 할 수도 있습니다.


먼저 반응은 잊어 버려라.
이것은 반응과 관련이 없으며 자바 스크립트의 기본 개념을 이해하도록하자. 예를 들어 자바 스크립트 (이름은 A)에 다음 함수를 작성했습니다.

function a() {

};

Q.1) 정의한 함수를 어떻게 호출하나요?
정답 : a ();

Q.2) 함수 참조를 후자라고 부를 수 있도록 전달하는 방법은 무엇입니까?
정답 : 재미있게하자 = a;

이제 질문에 와서 함수 이름과 함께 paranthesis를 사용했습니다. 즉, 다음 문이 렌더링 될 때 함수가 호출됩니다.

<td><span onClick={this.toggle()}>Details</span></td>

그렇다면 어떻게 수정합니까?
단순한!! 괄호를 제거하십시오. 이런 식으로 해당 함수의 참조를 onClick 이벤트에 제공했습니다. 구성 요소를 클릭 할 때만 함수를 다시 호출합니다.

 <td><span onClick={this.toggle}>Details</span></td>

One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue. Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.

{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}

https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578


if you don't need to pass arguments to function, just remove () from function like below:

<td><span onClick={this.toggle}>Details</span></td>

but if you want to pass arguments, you should do like below:

<td><span onClick={(e) => this.toggle(e,arg1,arg2)}>Details</span></td>

ReactJS: Maximum update depth exceeded error

inputDigit(digit){
  this.setState({
    displayValue: String(digit)
  })

<button type="button"onClick={this.inputDigit(0)}>

why that?

<button type="button"onClick={() => this.inputDigit(1)}>1</button>

The function onDigit sets the state, which causes a rerender, which causes onDigit to fire because that’s the value you’re setting as onClick which causes the state to be set which causes a rerender, which causes onDigit to fire because that’s the value you’re… Etc


onClick you should call function, thats called your function toggle.

onClick={() => this.toggle()}

참고URL : https://stackoverflow.com/questions/48497358/reactjs-maximum-update-depth-exceeded-error

반응형