我正在创建仪表板,其中点击选项卡上有4个选项卡,加载了不同的面板,并且在我的代码中加载了面板图表,componentDidMount
以及componentDidUpdate
当我点击时不同的选项卡正常运行,但当我点击相同的选项卡时,它会进入无限循环,所以当我点击相同的选项卡两次时,如何避免无限循环。
class BarChartComponent extends React.Component
{
constructor(props)
{
super(props);
this.state = {
data: null
}
};
componentDidMount()
{
var that = this;
$.ajax({
method: "GET",
url: "/querydata?query_id="+that.props.id,
success: function(data)
{
console.log("component did mount method called");
console.log(1,JSON.stringify(data));
var BarChartData = [
{
key: "totals",
values: []
}
];
data['data'].forEach(function (d)
{
d.value= +d.value
BarChartData[0].values.push(d)
})
console.log(2,JSON.stringify(BarChartData))
that.setState({data:BarChartData});
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
console.error("Status: " + textStatus);
console.error("Error: " + errorThrown);
}
});
}
componentDidUpdate(prevProps, prevState)
{
var that = this;
$.ajax({
method: "GET",
url: "/querydata?query_id="+that.props.id,
success: function(data)
{
console.log("component did update method called");
var BarChartData = [
{
key: "totals",
values: []
}
];
data['data'].forEach(function (d)
{
d.value= +d.value
BarChartData[0].values.push(d)
})
if( _.isEqual(prevState.data , that.state.data ))
{
that.setState({data:BarChartData});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
console.error("Status: " + textStatus);
console.error("Error: " + errorThrown);
}
});
}
render()
{
if (this.state.data==null)
{
return (<h1>Loading...</h1>);
}
return (
<NVD3Chart type="discreteBarChart" datum={this.state.data} x="name" y="value" yAxis={{
axisLabel:'Health Score'}} xAxis={{ axisLabel: 'Spines'}} />
);
}
}
window.BarChartComponent = BarChartComponent;
答案 0 :(得分:0)
它正在发生,因为您正在更新componentDidUpdate
功能中的状态。当您这样做时,您会触发另一次更新,因此它会再次调用componentDidUpdate
函数并重新执行此操作。您需要在componentDidUpdate
或shouldComponentUpdate
函数中添加某种类型的检查,以防止不必要的更新。您可以尝试将ajax调用包装在if语句中:if(prevState.data !== this.state.data)
。