2017-07-10 20 views
1

エラーmaximum call stack size exceededがあります。多分私は間違った方法でcomponentDidUpdateを理解していますが、それは1000回ではなく、一度実行してはいけません。呼び出しスタックの最大サイズを超えました。React-Redux

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引数とcomponentDidUpdateメソッドの代わりにcomponentWillUpdateメソッドを使用する必要があります。

// 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あなたは何を達成しようとしていますか? –

関連する問題