【问题标题】:Listen for changes in Formik field using ref and useEffect使用 ref 和 useEffect 监听 Formik 字段的变化
【发布时间】:2021-01-09 08:26:04
【问题描述】:

我正在尝试使用 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,但是当MyFormFieldName 更改时,这仍然不会导致useEffect 触发。

【问题讨论】:

    标签: reactjs formik


    【解决方案1】:

    您收到错误是因为在组件初始化时,current 属性为 null / undefined,而您正在尝试访问它的属性 (state)。

    另外,把hook传给依赖数组好像没有你想要的效果,总之好像有no effect:

    React Hook useEffect 有一个不必要的依赖:‘formikRef.current’。排除它或删除依赖数组。像‘contentRef.current’这样的可变值不是有效的依赖,因为改变它们不会重新渲染组件

    您的问题的解决方法(在之前链接文章的末尾描述)是在初始化后将 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 上使用示例。

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 2021-08-13
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2020-08-13
      相关资源
      最近更新 更多