未捕获的TypeError:无法在React中读取未定义的属性'showBarChart'

时间:2017-12-27 21:50:36

标签: javascript reactjs nvd3.js

我有一个自定义nvd3 scatterChart图的工具提示的函数。在我想要更新状态的函数中,所以我调用另一个执行setState的函数:

chart.tooltip.contentGenerator(function (d) {
      var html = "<div>";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
             // THIS FUNCTION UPDATES STATE
             this.showBarChart(elem.key);

              var expr = outer_obj["values"][0]["expr"];
              html += "<p>" + elem.key + "</p>";
              html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";
          }
        });
      })
      html += "</div>";
      return html;
    }).bind(this);

我在构造函数中有:

class ScatterChart extends React.Component {
  constructor(props){
  super(props);
  this.createScatterChart = this.createScatterChart.bind(this);
  this.showBarChart = this.showBarChart.bind(this);
  this.state = {
      neuron_name: ""
  }
}

render

render() {
console.log(this.state.neuron_name);
  return <div width={500} height={500}>
          <svg ref={node => this.node = node} width={500} height={500}></svg>
          <BarChart datum = { expressionDatum.getDatumForNeuron(this.state.neuron_name) }/>
        </div>
}

如何让contentGenerator函数看到this对象?

1 个答案:

答案 0 :(得分:0)

我可以通过分配that = this然后访问that来设置状态:

 var that = this;
    chart.tooltip.contentGenerator(function (d) {
      var html = "<div>";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
              that.showBarChart(elem.key);
              var expr = outer_obj["values"][0]["expr"];
              html += "<p>" + elem.key + "</p>";
              html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";

          }
        });
      })
      html += "</div>";
      return html;
    });

虽然当nvd3像疯了一样打印tooltips时会导致一个奇怪的错误,但我可以更新状态。