本文介绍了ReactJS:最大更新深度超出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ReactJS中切换组件的状态但是我收到一条错误说明:

I am trying to toggle the state of a component in ReactJS but I get an error stating:

我没有在代码中看到无限循环,任何人都可以帮助?

I don't see the infinite loop in my code, can anyone help?

ReactJS组件代码:

ReactJS component code:

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;


推荐答案

因为你在render方法中调用toggle导致重新渲染和切换将再次调用并重新渲染,依此类推

that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on

此行代码

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

你需要点击 onClick 参考 this.toggle 没有打电话

you need to make onClick refer to this.toggle not calling it

修复问题这样做

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

这篇关于ReactJS:最大更新深度超出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:24