【问题标题】:how to call a function inside if condition in class component react?如果类组件中的条件发生反应,如何在内部调用函数?
【发布时间】:2021-03-08 12:38:15
【问题描述】:

我是一个反应初学者,我试图在 if 条件下调用一个函数。我想如果条件为真,则将状态对象的值设置为 1,或者简单地调用一个将值设置为 1 的函数。 以下是我的代码:

class CountWalls extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            leftcount : 0,
            rightcount : 0
        }
    }
    setright = () =>{ 
         this.setState({rightcount: 1});    
    }
    setleft = () =>{ 
         this.setState({leftcount: 1});
    }
}
    render(){
    const arr = [4, 1, 1, 3, 2];
    let max = 0;
    max = Math.max(...arr);
    if(arr[0] <= max){ this.setleft() }
    if(arr[arr.length - 1] <= max){ this.setright() }  
        return(
            <>
             <h2>Right count: {this.state.rightcount}</h2>
             <h2>Left count: {this.state.leftcount}</h2>
            </>
        );
    }
}

我没有参加任何试验,只是卡在这里错误:请回答 enter image description here 错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

如果我从这样的函数调用中删除 () 括号{this.setleft},我会收到以下错误:

src\component\CountWalls.js 第 21:29 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions 第 22:42 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions

【问题讨论】:

  • 该错误准确描述了正在发生的事情,您正在调用诸如 setright in render 中的函数,该函数调用了 setState。而是只计算componentDidMount 中leftcount 和rightcount 的值,然后调用setState 一次。
  • 每当您调用 setState 时,都会重绘组件。因此,当您在 render() 中设置了 setRight 和 setleft 时,您正在生成一个无限循环。您可以使用构造函数或 componentDidMount 来初始化数据。 reactjs.org/docs/state-and-lifecycle.html

标签: javascript reactjs


【解决方案1】:

您不应该在没有 HTML 事件的情况下更新 render 方法中的状态。 否则会无限循环

你可以使用下面的代码来做到这一点

    class CountWalls extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                leftcount : 0,
                rightcount : 0
            }
        }

       componentDidMount(){
            const arr = [4, 1, 1, 2, 3];
            let max = 0;
            max = Math.max(...arr);
            if(arr[0] <= max){  this.setleft() }
            if(arr[arr.Length - 1] <= max){  this.setright() }
            console.log(this.state.rightcount);
        }
        setright = () =>{ 
             this.setState({rightcount: 1});    
        }
        setleft = () =>{ 
             this.setState({leftcount: 1});
        }
        render(){
           
            return(
                <>
                 <h2>Right count: {this.state.rightcount}</h2>
                 <h2>Left count: {this.state.leftcount}</h2>
                </>
            );
        }
    }

【讨论】:

  • @BhartiPatle 欢迎。如果它有效,那么请将我的答案标记为正确
  • 继续上面的代码,我有两个使用数组值的for循环,我不能在componentdidmount中放置for循环。我该怎么做?
  • 我已经修改了原始代码并用for循环逻辑(完整代码)更新了它,但是for循环没有运行。左右计数仅由 setstate 设置为 1
猜你喜欢
  • 2020-08-20
  • 2021-03-22
  • 2020-02-26
  • 1970-01-01
  • 2021-09-10
  • 2017-12-11
  • 1970-01-01
  • 2020-10-26
  • 2019-07-02
相关资源
最近更新 更多