即使在设置值后,useState 变量也会获取初始 null 值
我正在尝试使用 Chartjs 和 useEffect 生成条形图,我正在调用generateChart方法,在chartS变量中设置新的图表对象。但在初始加载中,如果我单击一个栏,onClick 函数中调用的 filterChart 方法仅具有初始 null 值,但
const dispatch = useDispatch();
const filters = useSelector((state) => {
return state.filters;
});
const generateChart = () => {
getData().then((data) => {
if (chartS) {
chartS.destroy();
}
setChartS(new ChartJS(document.getElementById("chart"), {
type: "bar",
options: {
responsive: true,
onClick: (e, legendItem) => {
if (legendItem[0]) {
filterCharts(e.chart, legendItem[0].element.$context.dataIndex);
}
}
},
data: chartJsData(data)
}));
});
}
useEffect(() => {
generateChart();
}, [filters]);
上面的图表对象不是从 onClick 调用 filterChart 的生成方法。 filterChart 函数如下,
const [chartS, setChartS] = useState(null);
const filterCharts = (chartObj, index) => {
console.log("chartS", chartS); /// this is still null though we set that using setChartS in getData function
if (chartObj?.data?.labels[index]) {
if (filters && filters.years && filters?.years?.includes(chartObj?.data?.labels[index]) && filters.years.length === 1) {
return;
}
dispatch({
type: "removeAllAddYear",
payload: chartObj.data.labels[index]
});
}
}
为什么我收到空值而不是在generateChart 函数中更新的新图表对象?
I'm trying to generate a bar chart using chartjs with the useEffect i'm calling the generateChart method setting the new chart object in chartS variable. but in the initial load if I clicked on a bar, the filterChart method gets called in the onClick function only has the initial null value but not the chart object
const dispatch = useDispatch();
const filters = useSelector((state) => {
return state.filters;
});
const generateChart = () => {
getData().then((data) => {
if (chartS) {
chartS.destroy();
}
setChartS(new ChartJS(document.getElementById("chart"), {
type: "bar",
options: {
responsive: true,
onClick: (e, legendItem) => {
if (legendItem[0]) {
filterCharts(e.chart, legendItem[0].element.$context.dataIndex);
}
}
},
data: chartJsData(data)
}));
});
}
useEffect(() => {
generateChart();
}, [filters]);
above is the generate method calling the filterChart from the onClick. The filterChart function is as follows,
const [chartS, setChartS] = useState(null);
const filterCharts = (chartObj, index) => {
console.log("chartS", chartS); /// this is still null though we set that using setChartS in getData function
if (chartObj?.data?.labels[index]) {
if (filters && filters.years && filters?.years?.includes(chartObj?.data?.labels[index]) && filters.years.length === 1) {
return;
}
dispatch({
type: "removeAllAddYear",
payload: chartObj.data.labels[index]
});
}
}
Why do I receive a null value instead of the new chart object which was updated in the generateChart function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论