reactjs - 如何解决React中的 "Invalid hook call"错误

标签 reactjs react-hooks formik react-dom yup

我正在构建一个与 Formik 和 Yup 库 react 的基本表单。该表单包含两个字段,电子邮件和密码;应该从用户那里获取值并将其打印在控制台中。 现在我面临的问题是 Hook 调用错误,即使我在代码中没有使用任何 Hook!

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. ..
2. ..
3. ..

我已经对这个错误进行了研究,并尝试了它建议的所有可能的方法。目前还没有什么帮助。我只运行一个版本的 React,据我所知,我也没有违反钩子(Hook)规则。有人可以帮我检测一下这里的问题吗?

我的代码:

登录表单.js

const validationSchema = Yup.object().shape({
      email: Yup.string()
      .email("Email is not valid")
      .required("Email is required"),
      password: Yup.string()
        .min(6, "Minimum 6 characters required")
        .required("Password is required"),
    })

    class LoginForm extends React.Component {
      render() {
        return (
          <div>
            <Formik
              initialValues={{ email: "", password: "" }}
              validationSchema={validationSchema}
              onSubmit={(values) => this.props.handleFormUpdate(values)}
            >
              <Form>
                <label>
                  Email<Field type="email" name="email"></Field>
                </label>
                <ErrorMessage name="email" component="div"></ErrorMessage>
                <label>
                  Password<Field type="password" name="password"></Field>
                </label>
                <ErrorMessage name="password" component="div"></ErrorMessage>
                <button type="submit">Submit</button>
              </Form>
            </Formik>
          </div>
        );
      }
    }
    export default LoginForm;

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
    };
  }
  handleFormUpdate(values) {
    console.log(values.email);
    console.log(values.password);
  }
  render() {
    return (
      <div>
        <LoginForm
          handleFormUpdate={this.handleFormUpdate.bind(this)}
        ></LoginForm>
      </div>
    );
  }
}

export default App;

最佳答案

这是因为 formik v2 是构建在 React hooks 之上的。要解决这个问题,您需要将使用 formik 的类组件转换为功能组件。 这是 formik 中重大更改的链接.

[编辑]或者您可以通过使用高阶组件 withFormik()

包装组件来使用 Component 类来实现此操作

关于reactjs - 如何解决React中的 "Invalid hook call"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244727/

相关文章:

reactjs - 如何在 React Native 中提交 Formik 表单后显示错误警报

javascript - 为什么输入元素没有与 React 中的其他数据一起排序?

javascript - 在 React ES6 中使用三种变量定义哪个更好?为什么?

javascript - 如果选择所有值,则显示列表中的所有结果

reactjs - 在 useEffect Hook 中设置状态以及 AsyncStorage 会导致无限循环?

javascript - 在自定义 Hook 和组件中使用 useEffect 有什么区别

javascript - 使用 jest/enzyme 对 formik 组件进行单元测试

reactjs - zsh : command not found: netlify on mac OS

javascript - 使用 useNavigate 和 state 进行重定向似乎很难完成

reactjs - 在 useEffect 中访问 Formik 的 setValues