我有一个反应组件,它接收两个输入:数据和规范化器。
<ChartInterface
normalizer={[10, 10, 10, 10]}
data={[
{ name: "lineA", data: [2, 1, 1, 2] },
{ name: "lineB", data: [1, 0, 3, 0] }
]}
/>
该ChartInterface
组件应呈现一个复选框和一个图表;如果未选中该复选框,则应仅使用数据绘制图表,效果很好;如果选中此复选框,则组件应将所有data
数组除以normalizer
数组,我已编写了此函数。
但是,问题是当我反复选中和取消选中此复选框时,数据不断被数组一遍又一遍地划分。
仅当我添加该<HighchartsReact options={chartOptions} highcharts={Highcharts} />
组件时,如果我将其注释掉并仅打印chartOptions.lineData
复选框,此问题将按预期工作。(选中该复选框将显示规范化数据,而取消选中则将显示原始数据作为道具提供)
ChartInterface组件:
const ChartInterface = (props) => {
// state for checkbox if chart needs to be normalized or not
const [isNormalized, setIsNormalized] = useState(false);
//divides one array by another, element-wise
function normalize(a, b) {
return a.map(function (x, idx) {
return x / b[idx];
});
}
// get data for lines
let lineData = props.data;
//if normalized is checked, normalize the data
if (isNormalized) {
lineData = lineData.map((line) => {
return {
name: line.name,
data: normalize(line.data, props.normalizer)
};
});
}
// Chartoptions for highcharts, here we add the line data
const chartOptions = {
chart: { type: "area" },
xAxis: {
type: "category",
crosshair: true
},
plotOptions: {
area: {
stacking: "normal",
lineWidth: 1
}
},
series: lineData
};
return (
<>
<input
type="checkbox"
checked={isNormalized}
onChange={(e) => setIsNormalized(e.target.checked)}
/>
Normalise the data ?
{<HighchartsReact options={chartOptions} highcharts={Highcharts} />}
{JSON.stringify(lineData)}
</>
);
};
我还制作了一个代码沙箱示例,您可以在其中通过选中和取消选中复选框轻松地查看问题所在:问题的codeandbox演示感谢您的帮助
尝试通过更新状态来更改数据。如何完成您可以在这里找到:https://stackblitz.com/edit/react-6qlksy?file = index.js
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句