问题
I have a function that customizes tooltip of nvd3
scatterChart
plot. In the function I want to update state, so I am calling another function that does 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);
Inside the constructor I have:
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: ""
}
}
And 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>
}
How could I make contentGenerator
function see this
object?
回答1:
I was able to set the state by assigning that = this
and then accessing 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;
});
Although it lead to a weird bug when nvd3
prints tooltips
like crazy, I can update the state.
来源:https://stackoverflow.com/questions/47999062/uncaught-typeerror-cannot-read-property-showbarchart-of-undefined-in-react