使用 ref 和 useEffect 监听 Formik 字段的变化
Listen for changes in Formik field using ref and useEffect
我正在尝试使用 Formik 中的 ref
让 useEffect
监听表单字段值的变化。但是当我 运行:
const formikRef = useRef(); // this gets passed to Formik's ref prop on component render
React.useEffect(() => {
// do something
}, [formikRef.current.state.values.MyFormFieldName]);
失败并出现此错误:Cannot read property 'state' of undefined
我使用的是 Formik v1.3,但我无法直接访问 Field 组件,因为我使用的是自定义包装器组件(作为内部 UI 库的一部分)并且它不会公开所有 Field 道具。
编辑:
我可以做到 formikRef.current?.state.values.MyFormFieldName
但这仍然不会导致 useEffect 在 MyFormFieldName
更改时触发。
您收到错误是因为当组件初始化时,current
属性 是 null / undefined
并且您正在尝试访问 属性 (state
) 的。
另外,把hook传给dependency数组好像没有达到你想要的效果,总之好像有no effect:
React Hook useEffect has an unnecessary dependency: ‘formikRef.current’. Either exclude it or remove the dependency array. Mutable values like ‘contentRef.current’ aren’t valid dependencies because mutating them doesn’t re-render the component
您的问题的解决方法(在先前链接的文章末尾进行了描述)是在初始化后将 ref 保存在状态中:
const App = (props) => {
const [formik, setFormik] = React.useState();
const formikRef = (node) => {
if (node !== null) {
setFormik(node.getBoundingClientRect().height);
}
};
React.useEffect(() => {
// do something
}, [formik]);
return (
<div ref={formikRef}>
<span>Hello Bro</span>
</div>
);
};
您可以尝试 Codepen 上的示例。
我正在尝试使用 Formik 中的 ref
让 useEffect
监听表单字段值的变化。但是当我 运行:
const formikRef = useRef(); // this gets passed to Formik's ref prop on component render
React.useEffect(() => {
// do something
}, [formikRef.current.state.values.MyFormFieldName]);
失败并出现此错误:Cannot read property 'state' of undefined
我使用的是 Formik v1.3,但我无法直接访问 Field 组件,因为我使用的是自定义包装器组件(作为内部 UI 库的一部分)并且它不会公开所有 Field 道具。
编辑:
我可以做到 formikRef.current?.state.values.MyFormFieldName
但这仍然不会导致 useEffect 在 MyFormFieldName
更改时触发。
您收到错误是因为当组件初始化时,current
属性 是 null / undefined
并且您正在尝试访问 属性 (state
) 的。
另外,把hook传给dependency数组好像没有达到你想要的效果,总之好像有no effect:
React Hook useEffect has an unnecessary dependency: ‘formikRef.current’. Either exclude it or remove the dependency array. Mutable values like ‘contentRef.current’ aren’t valid dependencies because mutating them doesn’t re-render the component
您的问题的解决方法(在先前链接的文章末尾进行了描述)是在初始化后将 ref 保存在状态中:
const App = (props) => {
const [formik, setFormik] = React.useState();
const formikRef = (node) => {
if (node !== null) {
setFormik(node.getBoundingClientRect().height);
}
};
React.useEffect(() => {
// do something
}, [formik]);
return (
<div ref={formikRef}>
<span>Hello Bro</span>
</div>
);
};
您可以尝试 Codepen 上的示例。