reactjs - 在 React/Redux 中更新 D3 Chart

标签 reactjs d3.js redux

我在 Redux 应用程序中使用的 React 组件中有一个 D3(v3) 图表。处理我的 D3 图表更新以反射(reflect)我的 Redux 存储更改的最佳方法是什么?

现在,我在 React 组件中有一个函数调用图表的绘制,还有一个函数在调用 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' />)
  }
}

任何关于如何改进这个问题的替代方法、伪代码、想法或反馈都将不胜感激。

最佳答案

您采用的方法似乎很适合。

componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.

Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.

注意

componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false.

您可以从 here 阅读更多内容

如果你想在收到 newPropssetState() 使用 componentWillReceiveProps() ,它会为每个新 Prop 触发。

每次有新 Prop 时,使用您的Chart API 进行绘制。

    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' />)
      }
    }

关于reactjs - 在 React/Redux 中更新 D3 Chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731422/

相关文章:

javascript - 将 observable 适配到 D3 但网页中没有任何渲染

json - Topojson 示例数据的含义是什么?

javascript - 终极版。将状态值传递给 reducer

reactjs - 编写 enzyme 测试时何时使用 "Component.WrappedComponent"

css - react / typescript : Idiomatic code for custom components that merge attributes?

javascript - 无法在React中使用d3.js绘制条形图

javascript - 这对于获取输入状态值有效吗?

react-native - 导入的 createStackNavigator 未定义

git - "src"属性中的模式不匹配任何文件“React.js

node.js - 使用 webpack 在 Node 服务器上渲染 React 组件