我目前正在使用 reactjs 制作仪表板,其中有 4 个选项卡或按钮图表正在正确创建但唯一的问题是当我们单击不同的仪表板并且它在同一面板中具有相同的图表而不是图表未更新我已经使用了两者componentDidMount() 和 componentDidUpdate 虽然它提供了正确的输出但它创建了一个无限循环我也应用了一些条件但它仍然处于无限循环中任何人都可以帮助我吗??
这是我的代码
class BarChartComponent extends React.Component
{
constructor(props)
{
super(props);
this.state = {
data: null
}
};
componentDidMount()
{
var that = this;
$.ajax({
method: "GET",
url: "http://10.0.3.8:8050/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.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)
{
if(prevState.data !== this.state.data )
{
var that = this;
$.ajax({
method: "GET",
url: "http://10.0.3.8:8050/querydata?query_id="+that.props.id,
success: function(data)
{
console.log("component did update method called");
var BarChartData = [
{
key: "totals",
values: []
}
];
data.forEach(function (d)
{
d.value= +d.value
BarChartData[0].values.push(d)
})
if( prevProps.id !== that.state.id )
{
that.setState({data:BarChartData});
console.log(3,JSON.stringify(BarChartData))
console.log(4,JSON.stringify(that.state.data))
}
},
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"/>
);
}
}
window.BarChartComponent = BarChartComponent;
最佳答案
if(prevState.data !== this.state.data)
不比较实际对象是否相等。这就是为什么我假设您的 $.ajax
请求在 componentDidUpdate
中连续触发,即使实际数据相同。
如果你真的想采用昂贵的方式,你可以使用 lodash
(_.isEqual
) 来比较对象(或 jQuery 中的内置方法)。不过,出于性能原因,最终它是比较特定数据的更好方法。
关于javascript - 如何在 reactjs 的 componentDidUpdate 中打破无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43998643/