我有一个带有react-chartjs-2的图表,该图表是可拖动的。我使用useRef挂钩获取更新的图表数据的值,并在触发提交函数时更新useContext上下文,如下所示:
const handleSubmit = () => {
console.log('SUBMITTED');
const essentialsKeys = Object.keys(retirementSpending.essentials);
let _tempEssentials = {};
for (let i = 0; i < essentialsKeys.length; i++) {
_tempEssentials[essentialsKeys[i]] = retirementSpendingRef.current.chartInstance.data.datasets[0].data[i];
}
console.log('CURRENT ESSENTIALS', _tempEssentials);
const _tempRetirementSpending = {
essentials: _tempEssentials,
comforts: { ...retirementSpending.comforts },
luxuries: { ...retirementSpending.luxuries }
};
console.log('TEMP RETIREMENT SPENDING', _tempRetirementSpending);
dispatch({ type: setRetirementAge, payload: { retirementAge: retirementAge } });
dispatch({
type: setRetirementSpending,
payload: { isCouple: context.state.playerInfo.couple, retirementSpending: _tempRetirementSpending }
});
};
在页面上,我还显示了来自getAnnualSpending函数的值,该函数返回在初始化状态退休支出时根据组件初始化数据集计算得出的值。
const getAnnualSpending = () => {
const essentials = Object.keys(retirementSpending.essentials);
const comforts = Object.keys(retirementSpending.comforts);
const luxuries = Object.keys(retirementSpending.luxuries);
let annualSpending = 0;
console.log('CHART INSTANCE', retirementSpendingRef.current);
if (retirementSpendingRef.current !== undefined) {
for (let i = 0; i < essentials.length; i++) {
annualSpending += retirementSpendingRef.current['chartInstance']['data']['datasets'][0]['data'][i];
}
} else {
for (let item of essentials) {
annualSpending += retirementSpending.essentials[item];
}
}
for (let item of comforts) {
annualSpending += retirementSpending.comforts[item];
}
for (let item of luxuries) {
annualSpending += retirementSpending.luxuries[item];
}
return annualSpending;
};
我希望此函数在每次更新rupingSpendingRef.current时进行动态更新(在触发路由器时会触发handleSubmit函数,因此将更新上下文,但是除非用户返回该页面,否则不会再次显示该页面。我需要根据图表更新动态触发功能getAnnualSpending。)-我该怎么做?
我尝试了三种不成功的方法:
如果我将retireingSpendingRef.current的值分配给一个状态,那么我需要一个处理函数来连续更新状态,否则我的图表将不再可拖动
如果每当retirementSpendingRef.current更新时,我尝试使用useEffect来更新上下文,useRef不会检测到更改,因此永远不会触发。
如果我仅在未定义retirementSpendingRef.current的情况下尝试显示该值,则它将永远不会显示,因为页面是在retirespendingRef.current可用之前渲染的,直到触发handleSubmit函数后才重新渲染。 p>
我认为我需要一个useCallback函数,但是我不知道如何从中获取数据来更新handleSubmit中的上下文?