我有一个名为useInitial的钩子,它被定义为
function useInitial(value) {
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Return previous value (happens before update in useEffect above)
return ref.current;
}
我在功能组件中使用它来存储字段的初始值
const Calculator = ({ current_field }) => {
const previousField = usePrevious(current_field);
const intialContent = useInitial(current_field.content);
useEffect(() => {
calculateTotals();
if (previousField) {
console.log({ intialContent });
console.log(previousField.content);
}
return () => {
//DO something here to clear and reset the value stored in intialContent.
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [current_field]);
return null;
};
如果CurrentField更改,我想要新字段的initialValue,而不是第一个字段。
我仔细考虑并找到了解决方案。
useInitial钩子可以修改为像一样使用inupt的deps数组
function useInitial(value, deps) {
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
// Return previous value (happens before update in useEffect above)
return ref.current;
}
然后使用它可以在deps数组中发送current_field。
const Calculator = ({ current_field }) => {
const previousField = usePrevious(current_field);
const intialContent = useInitial(current_field.content);
useEffect(() => {
calculateTotals();
if (previousField) {
console.log({ intialContent });
console.log(previousField.content);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [current_field]);
return null;
};
这将在字段更改后重新触发useInitial中的useEffect,并存储新字段的初始值。