【问题标题】:this.setState making infinite loop outside of array.map functionthis.setState 在 array.map 函数之外进行无限循环
【发布时间】:2017-12-08 16:29:13
【问题描述】:

我有这个数组映射函数来渲染一些东西...... 我有 5 个从 0 开始的变量,根据 switch 语句,每个变量的值都会增加 1。

renderUser = (index)=>{
    let C1Count = 0, C2Count = 0, C3Count = 0, C4Count = 0, C5Count = 0;
    let users = this.state.users.map((user,index)=>{

   // swiching some value , that is from 0 to 4

   switch(this.state.users[index].result){
      case 0: { C1Count += 1;   break; }
      case 1: { C2Count += 1;  break; }
      case 2: { C3Count += 1;  break; }
      case 3: { C4Count += 1;   break; }
      case 4: { C5Count += 1;   break; }
      default: { console.log("non");  break; };
    }
    return(
      ....stuff to render 
                   )


   }).reverse();



  return users;

}

我要更新5个状态

this.setState({
C1Count:C1Count, // state : variable value
C2Count:C2Count, // state : variable value
C3Count:C3Count, // state : variable value
C4Count:C4Count, // state : variable value
C5Count:C5Count  // state : variable value
});

如果我将 setState 代码放在 ...}).reverse(); 之后和 ..return users; 之前

我得到一个

已超过最大更新深度。这可能发生在组件 在 componentWillUpdate 内重复调用 setState 或 组件更新。 React 将嵌套更新的数量限制为 防止无限循环。

错误 .... 所以我的问题是...如何在所有循环完成并更新 C1Count, C2Count, C3Count, C4Count, C5Count 变量后更新状态。

【问题讨论】:

    标签: javascript arrays reactjs state


    【解决方案1】:

    当您setState() 时,您将导致另一个渲染,因此您的无限循环。你不应该从render 调用setStatelifecycle 方法之一(componentDidMount 等)将是一个更好的地方,具体取决于您的需要或constructor(如果这是组件的初始状态)。

    【讨论】:

    • 是的 .. 我设法用全局变量 this.C1Count , this.C2Count e.t. 完成了想要的操作
    【解决方案2】:

    默认情况下,当通过setState() 更改其状态时,React 组件将重新渲染,这就是为什么render() 应该是一个纯函数(即不要修改状态)。

    对于您的情况,Count 变量是派生状态,因此您实际上不需要保留该值。相反,您可以创建一个计算其值的函数:

    getCounts() {
      return this.state.users.reduce((counts, user) => {
        switch (user.result) {
          case 0: 
            counts.C1Count++; break;
          case 1:
            counts.C2Count++; break;
          case 2:
            counts.C3Count++; break;
          case 3:
            counts.C4Count++; break;
          case 4:
            counts.C5Count++; break;
          default:
            console.log("non");
        }
    
        return counts;
      }, { C1Count: 0, C2Count: 0, C3Count: 0, C4Count: 0, C5Count: 0 });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多