我有一个组件,它呈现与每个用户有关的饼图,其中每个用户都是唯一的值。当我点击一个特定用户的名字时,它应该用该指定用户的值重新呈现饼图。相反,第一次点击就会延迟,直到我点击另一个用户才会更新。例如(使用提供的链接),如果我点击用户'Bob Dickinson',直到我再次点击下一个用户'Eugine Smith',然后呈现与Bob Dickinson相关的数据但是以Eugine Smith的名字,并且该组件随后在每个渲染上落后。我在下面列出了我的代码,并在活生生的例子链接:组件未同步更新
链接:https://2b0057e3.ngrok.io/dashboard
StudentGraph组件:
import React from 'react';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';
import chart from 'chart.js';
export default class StudentGraph extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.plot = this.plot.bind(this);
}
plot(){
var ctx = document.getElementById("graph2");
var data = {
labels: [
"Budget Used",
"Budget Remaining"
],
datasets: [
{
data: [this.props.budgetUsed,this.props.budgetRemain ],
backgroundColor: [
"#FF6384",
"#90ee90"
],
hoverBackgroundColor: [
"#36A2EB",
"#36A2EB"
]
}]
};
var myChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
componentWillUpdate(){
this.plot()
}
render() {
return (
<div>
<h3>Budget Started: 10,250.00</h3>
<h3>Budget Used: {this.props.budgetUsed}</h3>
<h3>Budget Remaining: {this.props.budgetRemain}</h3>
<div style = {{ width: '20%'}}>
<canvas id="graph2" width="100" height="100"></canvas>
</div>
</div>
);
}
}
我想出了这个问题。道具正在更新,但我使用的是基于组件生命周期方法的旧道具价值。相反,我把它切换到componentDidUpdate,它抓住了新的道具,而不是去掉以前生成的值。 –