我试图通过添加到现有状态来使用React钩子更新事件监听器中的状态:
import React, { useState } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';
const LineChart = () => {
const [hoverData, setHoverData] = useState(null);
const [hoveredOverCategories, setHoveredOverCategories] = useState([]);
const [chartOptions, setChartOptions] = useState({
xAxis: {
categories: ['A', 'B', 'C'],
},
series: [
{ data: [1, 2, 3] }
],
plotOptions: {
series: {
point: {
events: {
mouseOver(e){
console.log(hoveredOverCategories); // Always prints the empty array `[]`
setHoverData(e.target.category);
setHoveredOverCategories(
[...hoveredOverCategories, e.target.category]
);
}
}
}
}
}
});
return (
<div>
<HighchartsReact
highcharts={Highcharts}
options={chartOptions}
/>
<h3>Hovering over {hoverData}</h3>
<ol>
{hoveredOverCategories.map(category => (
<li>Hovered over {category}</li>
))}
</ol>
</div>
)
}
render(<LineChart />, document.getElementById('root'));
但是,似乎事件监听器(mouseOver
)无法访问更新状态(hoveredOverCategories
):console.log(hoveredOverCategories);
总是打印空数组[]
。
预期结果是为每个mouseOver
事件添加了类别数组。参见this demonstration。但是实际发生的是仅使用最新值覆盖了数组。
(此复制品基于the documented optimal way to update,已证明here。)
请注意,我能够使用类组件获得预期的结果。
答案 0 :(得分:1)
我认为通过闭包访问hoveredCategories
并不是更精确的方法。我可以通过使用以前的状态访问它而不是依靠闭包值来使其工作:
mouseOver(e){
console.log(hoveredOverCategories);
setHoverData(e.target.category);
setHoveredOverCategories((prevHoveredOverCategories) => {
return [...prevHoveredOverCategories, e.target.category]
});
}
看看它是否有效:https://stackblitz.com/edit/highcharts-react-hook-state-event-listener-xxqscw