我试图使用useEffect和useRef()来获得我的计数器的最新值,以及与以前的值进行比较,以便我知道是否需要调用addValues或removeValues函数。
我遵循这里的指示,我正在使用Typescript,当我设置prevSubjectAddressCounterRef.current = subjectAddressCounter;
时,我得到错误TS2322: Type 'number' is not assignable to type 'undefined'.
如何修复此错误并确保在更新状态计数时使用的是最新值?
请参阅下面的相关代码。
const FormGroup = prop => {
const [subjectAddressCounter, setSubjectAddressCounter] = useState(0); // changing to 0 || undefined causes this not to function correctly because you can't add to undefined
const prevSubjectAddressCounterRef = useRef();
useEffect(() => {
prevSubjectAddressCounterRef.current = subjectAddressCounter; // this causes Typescript error above
if (prevSubjectAddressCounterRef.current < subjectAddressCounter) {
// call function to addValues
addValues();
}
if (prevSubjectAddressCounterRef.current === subjectAddressCounter) {
// call function to removeValues
removeValues();
}
}, [subjectAddressCounter]);
const addSection = section => {
if (section.section === SectionTitle.subjectAddress) {
setSubjectAddressCounter(prevCount => prevCount + 1);
}
};
const removeSection = section => {
if (section.section === SectionTitle.subjectAddress) {
setSubjectAddressCounter(prevCount => prevCount - 1);
}
};
return (
...
button onClick={() => addSection(form)}
button onClick={() => removeSection(form)}
)
}
我认为您需要传递初始值并定义const的类型,因为undefined
不等于number
,这就是抛出错误Type 'number' is not assignable to type 'undefined'
的原因。我觉得应该是这样的:
const prevSubjectAddressCounterRef = useRef<number>(0);