2016-11-21 15 views
0

Reduxアプリケーション内で使用されるReactコンポーネント内にD3(v3)チャートがあります。私のReduxストアの変更を反映するためにD3チャートの更新を処理する最善の方法は何ですか?React/Redux内のD3チャートの更新

は今のところ、私はそうとも呼ばれるグラフの描画とすぐcomponentWillUpdateとして、前のチャートの除去を呼び出す関数を呼び出すリアクトコンポーネント内の機能を持っている:

export default class Chart extends Component { 
    componentWillUpdate(nextProps) { 
    this.removePreviousChart(); 
    this.drawChart(nextProps.chartData); 
    } 
    removePreviousChart(){ 
    const chart = document.getElementById('chart'); 
    while(chart.hasChildNodes()) 
     chart.removeChild(chart.lastChild); 
    } 
    } 
    drawChart() { 
    //appends an svg to #chart html element and draws a d3 Chart 
    } 
    render(){ 
    this.drawChart(); 
    return(<div id='chart' />) 
    } 
} 

どれを代替アプローチ、擬似コード、アイデア、またはこの質問を改善する方法に関するフィードバックは高く評価されます。

答えて

1

あなたが従ったアプローチはうまくいくようです。

componentWillUpdate()は、新しい の小道具または状態が受信されたときにレンダリングの直前に呼び出されます。これを更新の前に準備を行う の機会として使用してください。このメソッドは、初期レンダリングでは とは呼ばれません。

ここでthis.setState()を呼び出すことはできません。小道具の変更に応じて 州を更新する必要がある場合は、代わりにcomponentWillReceiveProps() を使用してください。 shouldComponentUpdate場合

componentWillUpdate()がfalseを返す )(呼び出されることはありません。

あなたはすべての新しい小道具のために解雇されnewProps使用componentWillReceiveProps()を受けてsetState()したい場合は、here

からより多くを読むことができます。

新しい小道具があるたびに、ChartAPIを使用して描画します。

export default class Chart extends Component { 
     componentWillReceiveProps(nextProps) { 
     this.removePreviousChart(); 
     this.drawChart(nextProps.chartData); 
     } 
     removePreviousChart(){ 
     const chart = document.getElementById('chart'); 
     while(chart.hasChildNodes()) 
      chart.removeChild(chart.lastChild); 
     } 
     } 
     drawChart(chartData) { 
     const chart = document.getElementById('chart'); //fails if DOM not rendered 
     //appends an svg to #chart html element and draws a d3 Chart 
     //assuming you chart function as Chart(element, data); 
     if(chart && chartData){ //draw only if DOM rendered and have chartData 
      new Chart(chart, chartData); //calls to draw graph 
     } 
     } 
     render(){ 
     return(<div id='chart' />) 
     } 
    } 
+0

新しいコンポーネントおよび/または状態が受信されている場合にのみ、「componentWillUpdate」は起動しませんか?私はそれを介して 'componentWillReceiveProps'を使う利点が何であるか分かりません。明確にすることはできますか? – Matt16749

+0

@ Matt16749が私の答えを更新しました。それを一度チェックする –

関連する問題