我正在使用 useSelector
获取状态值以获取状态变量并尝试在事件处理程序中访问它。但总是得到一个陈旧的价值。
有人可以帮我解决这个问题吗?
import React, { ReactElement } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
AMPLITUDE_SELECTION,
FREQUENCY_UNIT,
MotionUnitTypes,
Actions,
} from '../../shared/features/workflow';
import AmplitudeUnit from './AmplitudeUnit';
import MotionUnit from './MotionUnit';
import FrequencyUnit from './FrequencyUnit';
/**
*
* @returns
*/
export function UnitsSelector(): ReactElement {
const dispatch = useDispatch();
const frequencyUnit = useSelector(
(state: any) => state.features.workflow.va.units.frequencyUnit
);
const amplitudeSelection = useSelector(
(state: any) => state.features.workflow.va.units.amplitudeSelection
);
const motionUnitType: MotionUnitTypes = useSelector(
(state: any) =>
state.features.workflow.va.units.motionUnit.selectedMotionUnitType
);
// ###### This is showing appropriate value
console.log(frequencyUnit, amplitudeSelection, motionUnitType);
const handleMotionUnitChange = (motionUnit: MotionUnitTypes) => {
// ###### This is giving stale value. Always shows value of previous state
console.log(frequencyUnit, amplitudeSelection, motionUnitType);
dispatch(
VAactions.updateSelectedMotionUnit(motionUnit, {
amplitudeSelection,
frequencyUnit,
motionUnitType: motionUnit,
enableHarmonics,
})
);
};
const handleAmplitudeUnitChange = (value: AMPLITUDE_SELECTION) => {
dispatch(
VAactions.updateAmplitudeSelection(value, {
amplitudeSelection: value,
frequencyUnit,
motionUnitType,
enableHarmonics,
})
);
};
const handleFrequencyUnitChange = (value: FREQUENCY_UNIT) => {
dispatch(
VAactions.updateFrequencyUnit(value, {
amplitudeSelection,
frequencyUnit: value,
motionUnitType,
enableHarmonics,
})
);
};
return (
<>
<FrequencyUnit
selectedValue={frequencyUnit}
handleChange={handleFrequencyUnitChange}
/>
<MotionUnit
selectedValue={motionUnitType}
handleChange={handleMotionUnitChange}
/>
<AmplitudeUnit
selectedValue={amplitudeSelection}
handleChange={handleAmplitudeUnitChange}
/>
</>
);
}
我知道这个问题是由于关闭而出现的,但无法为这个问题找到正确的解决方案。请帮忙。