javascript - 在 ComponentDidMount 中添加条件以显示图表数据
问题描述
我在 componentDidMount 中添加了一个条件,以根据收到的专业人士展示 1 个或 2 个数据集的数据。但是,我在 if 条件下遇到错误。这是 BarChart 组件。在其中,我已经从“chart.js”导入了图表。
class BarChart1 extends Component {
constructor(props) {
super(props);
}
chartRef = React.createRef();
componentDidMount() {
const myChartRef = this.chartRef.current.getContext("2d");
let dataCheck = null;
if(this.props.data2){
let dataCheck = {
labels: this.props.labels,
datasets: [
{
label: this.props.label1,
backgroundColor: 'rgba(26,179,148,0.5)',
borderColor: "rgba(26,179,148,0.7)",
data: this.props.data1
}, {
label: this.props.label2,
backgroundColor: 'rgba(220, 220, 220, 0.5)',
pointBorderColor: "#fff",
data: this.props.data2
}
]
}
}
else {
let dataCheck = {
labels: this.props.labels,
datasets: [
{
label: this.props.label1,
backgroundColor: 'rgba(26,179,148,0.5)',
borderColor: "rgba(26,179,148,0.7)",
data: this.props.data1
}
]
}
}
new Chart(myChartRef, {
type: 'bar',
data: {dataCheck},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
gridLines: {
display: false
}
}],
xAxes: [{
gridlines: {
display: false
},
ticks: {
fontSize: 9
}
}]
}
},
plugins: [{
beforeInit: function(chart) {
chart.data.labels.forEach(function(e, i, a) {
if (/\n/.test(e)) {
a[i] = e.split(/\n/);
}
});
}
}]
})
}
render() {
return <canvas ref={this.chartRef} />
}
}
我已经编辑了我的问题。我现在得到一个没有错误的空白图表。
解决方案
您的代码中有两个错误。
- 你必须用 ; 结束变量声明 代替 ,
- 您必须在 if else 块之外声明 datacheck ,除非您希望它未定义
componentDidMount() {
...
let dataCheck;
if(this.props.data2){
dataCheck = {
...
}
}
else {
dataCheck = {
...
}
}
}
推荐阅读
- python - 对于列表的每个元素,从不同的列表中找到最接近的日期
- javascript - 如何过滤反应中的唯一值?
- python - TensorFlow 无法正确导入
- ios - 自定义呈现的 UINavigationController 在转换期间与 UICollectionView 的 contentOffset 发生故障
- sql - ORA-01722: 在 Toad for Oracle 中执行选择后数字无效
- linux - 使用本机方法从 bash 中的 XML 文件中获取特定的嵌套值
- configuration - IIS 管理器仅显示 2 个图标(IIS 8 Server 2012 R2)
- java - 删除视图上的最小化/最大化按钮
- malloc - 带有 malloc() 函数的错误检查堆
- javascript - 有什么方法可以从网页上的另一个文本框中自动填写一个文本框?