【发布时间】:2020-11-02 22:43:22
【问题描述】:
我有一个接收两个输入的反应组件:数据和规范化器。
<ChartInterface
normalizer={[10, 10, 10, 10]}
data={[
{ name: "lineA", data: [2, 1, 1, 2] },
{ name: "lineB", data: [1, 0, 3, 0] }
]}
/>
ChartInterface 组件应该呈现一个复选框和一个图表;当未选中该复选框时,它应该只呈现一个包含数据的图表,效果很好;如果选中该复选框,则组件应将所有data 数组除以normalizerarray,我已经编写了这样做的函数。
但是,问题是当我反复选中和取消选中此复选框时,数据会一遍又一遍地被数组分割。
仅当我添加 <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)}
</>
);
};
我还制作了一个代码沙箱示例,您可以通过选中和取消选中复选框轻松查看问题所在:codesandbox demo of problem 谢谢你的帮助
【问题讨论】:
标签: javascript reactjs highcharts