2017-07-10 57 views
1

我有錯誤maximum call stack size exceeded。也許我以錯誤的方式理解componentDidUpdate,但不應該它運行一次,而是1000.如何解決它?最大調用堆棧大小超過陣營 - 終極版

class App extends Component { 
 

 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     amount: 0 
 
    } 
 
    } 
 

 
    updateAmout() { 
 
    let number = 0; 
 
    this.props.comments.map((comment, index) => { 
 

 
     if (comment.replyTo === null) { 
 

 
     number += 1; 
 
     this.setState({amount: number}); 
 
     } 
 
     return null; 
 
    }); 
 
    } 
 

 
    componentWillMount() { 
 
    this.updateAmout(); 
 
    } 
 

 
    componentDidUpdate() { 
 
    this.updateAmout(); 
 
    } 
 

 
    render() { 
 
    console.log(this.state.amount); 
 
    return (
 
     <div className="comments-container"> 
 
     <div id="comments"> 
 
      <AddComment /> 
 
      <div className="comments-flow"> 
 
      <div className="comments-header"> 
 
       <div className="pull-right"> 
 
       <a href="" className="text-muted">Best</a> | 
 
       <a href="" className="active">Newest</a> | 
 
       <a href="" className="text-muted">Oldest</a> 
 
       </div> 
 
       <b>6 Comments</b> 
 
      </div> 
 
      <RenderComments /> 
 
      </div> 
 
      <button className="btn btn-block">More...</button> 
 
     </div> 
 
     </div> 
 

 
    ) // return 
 
    } // render 
 
} // App

+1

'componentWillMount'將強制進行更新,這將觸發'componentDidUpdate'這將再次強制更新等等。 – MinusFour

+1

'componentDidUpdate()'是一個回調來通知您的狀態更新被成功完成。你不應該在這裏觸發另一個狀態更新。 –

回答

0

我找到了答案,我的問題。我需要使用nextProps參數和方法componentWillUpdate而不是componentDidUpdate方法。

// before 
 
componentDidUpdate() { 
 
this.updateAmout(); 
 
} 
 

 
// after 
 
componentWillUpdate(nextProps) { 
 
    if (!_.isEqual(this.props, nextProps)) { 
 
    this.updateAmout(); 
 
    } 
 
}

5

每次在componentDidUpdate修改狀態,重新繪製的異步引發。 在您的方法updateAmount中,您正在修改狀態。 您在調用該方法在componentDidUpdate,所以你開始重新呈現一個無限循環,所以終於創造了這個死循環浪費的JavaScript內存。

時更新所述狀態是以下一項所述的陣營週期。所以你可以很容易地理解爲什麼你進入一個無限循環。 enter image description here

+0

我該如何解決它? –

+0

在javascript事件(例如點擊)後執行'updateAmount'並重做一些邏輯。您也可以使用'shouldComponentUpdate'來檢查是否可以執行重新渲染,儘管這對性能不利。 – Dez

+0

@RamzanChasygov你想完成什麼? –

相關問題