简体   繁体   English

在渲染 function 中设置条件并更改 state

[英]set a condition inside render function and change state

I want to set a condition inside the render function.我想在渲染 function 中设置一个条件。 The code is as below:代码如下:

class ListItems extends React.Component{
    constructor(){
        super();
        this.state = {
            active:false,   
        }
        this.toggleActive = this.toggleActive.bind(this);
    }
    toggleActive(){
        this.setState({
            active: !this.state.active
        })
    }   
    render(){   
        var demo = document.querySelector("#" + this.props.data);
        if(document.body.contains(demo)){
            this.toggleActive()
            return(
                <li className={this.state.active ? "active" : ""} onClick={this.toggleActive}>{this.props.data}</li>
            )
        }   
        else{
            return(
                <li className={this.state.active ? "active" : ""} onClick={this.toggleActive}>{this.props.data}</li>
            )
        }   
    }
}

it compiles successfully but returns this error while running:它编译成功,但在运行时返回此错误:

Maximum update depth exceeded.超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React 限制了嵌套更新的数量以防止无限循环。

use this:用这个:

class ListItems extends React.Component{
    constructor(){
        super();
        this.state = {
            active:false,   
        }
        this.toggleActive = this.toggleActive.bind(this);
    }
    toggleActive(){
        this.setState({
            active: !this.state.active
        })
    }   
    componentDidMount(){
        var demo = document.querySelector("#" + this.props.data);
        if(document.body.contains(demo)){
            this.toggleActive()
            return(
                <li className={this.state.active ? "active" : ""} onClick={this.toggleActive}>{this.props.data}</li>
            )
        }   
    }
    render(){   
        return(
            <li className={this.state.active ? "active" : ""} onClick={this.toggleActive}>{this.props.data}</li>
        )
    }
}

let me know if that works?让我知道这是否有效?

In your render you have this.toggleActive() which changes the state, causing a rerender, and which then again changes state, so this causes an intinite loop.在您的渲染中,您有 this.toggleActive() 更改 state,导致重新渲染,然后再次更改 state,因此这会导致无限循环。

Just remove this line and try.只需删除此行并尝试。

If you want to change state you can use componentDidMount lifecycle:如果你想改变 state 你可以使用 componentDidMount 生命周期:

componentDidMount() {
   this.toggleActive();
}

Change the code to following, you are basically calling the functions while rendering.将代码更改为以下,您基本上是在渲染时调用函数。

onClick={ e => {// your code} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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