微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

挂钩错误:Next.js和材料UI表单验证

如何解决挂钩错误:Next.js和材料UI表单验证

我正在尝试为我的用户设置一个对话框/模式以订阅新闻通讯。 当它是普通的React应用程序时,代码可以完全正常工作,但目前我正在转换为Next.js。现在,我收到一个RuntimeError,抱怨钩子配置不正确。早些时候,我遇到了使Material UI与next.js一起运行的问题。但这是可以解决的。但是我在这里迷路了,有人知道发生了什么事吗?

我的组件:

import { TextValidator,ValidatorForm } from "react-material-ui-form-validator";

import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import { Grid } from "@material-ui/core";
import React from "react";
import Slide from "@material-ui/core/Slide";



export default function EmailPopUp() {

  const [showOpen,setShowOpen] = React.useState(true);
  const [open,setopen] = React.useState(showOpen);
  const [form,setForm] = React.useState({
    submitted: false,formData: { email: "" },});
  const refInput = React.useRef("form");

  const isbrowser = () => typeof window !== "undefined";

  const handleClickOpen = () => setopen(true);

  const handleClose = () => setopen(false);



  const handleChange = (event) => {
    const { formData } = form;
    formData[event.target.name] = event.target.value;
    setForm({ formData });
  };

  const handleSubmit = () => {
    this.setForm({ submitted: true },() => {
      formSubmitaction();
    });
  };

  const formSubmitaction = () => {
    fetch(`${process.env.NEXT_PUBLIC_BACKEND_API}subscribe_newsletter/`,{
      method: "POST",headers: {
        Accept: "application/json","Content-Type": "application/json",},body: JSON.stringify({
        email: form.formData.email,}),}).finally(handleClose());
  };

  const Transition = React.forwardRef(function Transition(props,ref) {
    return <Slide direction="up" ref={ref} {...props} />;
  });

  return (
    isbrowser && (
      <div className="dialog-container">
        <Dialog
          disableBackdropClick={true}
          open={open}
          TransitionComponent={Transition}
          keepMounted
          onClose={handleClose}
          aria-labelledby="alert-dialog-slide-title"
          aria-describedby="alert-dialog-slide-description"
        >
          <DialogTitle id="alert-dialog-slide-title">
            Newsletter
          </DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-slide-description">
              <Grid container spacing={2} justify="center">
                <Grid item xs="auto">
                  <img
                    src="/images/newsletter-img.jpg"
                    className="newsletter-image"
                  />
                </Grid>
                <Grid item xs="auto">
                  <div className="dialog-content">
              
                  </div>
                  <ValidatorForm ref={refInput} onSubmit={handleSubmit}>
                    <TextValidator
                      label="Email"
                      onChange={handleChange}
                      name="email"
                      value={form.formData.email}
                      validators={["required","isEmail"]}
                      errorMessages={[
                        "this field is required","email is not valid",]}
                    /> 
                    <div className="newsletter-button">
                      <Button
                        type="submit"
                        variant="contained"
                        color="secondary"
                      >
                        Subscribe
                      </Button>
                    </div>
                  </ValidatorForm>
                </Grid>
              </Grid>
            </DialogContentText>
          </DialogContent>
        </Dialog>
      </div>
    )
  );
}

堆栈跟踪:

Unhandled Runtime Error
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. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See  for tips about how to debug and fix this problem.

Call Stack
resolvedispatcher
../node_modules/react/cjs/react.development.js (1465:0)
Object.useContext
../node_modules/react/cjs/react.development.js (1473:0)
useTheme
../node_modules/@material-ui/styles/esm/useTheme/useTheme.js (4:19)
useStyles
../node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js (222:24)
WithStyles
../node_modules/@material-ui/styles/esm/withStyles/withStyles.js (55:0)
renderWithHooks
node_modules/react-dom/cjs/react-dom.development.js (14803:0)
updateForwardRef
node_modules/react-dom/cjs/react-dom.development.js (16816:0)
beginWork
node_modules/react-dom/cjs/react-dom.development.js (18645:0)
HTMLUnkNownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js (188:0)
Object.invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js (237:0)
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js (292:0)
beginWork$1
node_modules/react-dom/cjs/react-dom.development.js (23203:0)
performunitOfWork
node_modules/react-dom/cjs/react-dom.development.js (22154:0)
workLoopSync
node_modules/react-dom/cjs/react-dom.development.js (22130:0)
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js (21756:0)
eval
node_modules/react-dom/cjs/react-dom.development.js (11089:0)
unstable_runWithPriority
node_modules/scheduler/cjs/scheduler.development.js (653:0)
runWithPriority$1
node_modules/react-dom/cjs/react-dom.development.js (11039:0)
flushSyncCallbackQueueImpl
node_modules/react-dom/cjs/react-dom.development.js (11084:0)
flushSyncCallbackQueue
node_modules/react-dom/cjs/react-dom.development.js (11072:0)
flushSync
node_modules/react-dom/cjs/react-dom.development.js (21932:0)
Object.scheduleRefresh
node_modules/react-dom/cjs/react-dom.development.js (11626:0)
eval
node_modules/react-refresh/cjs/react-refresh-runtime.development.js (304:0)
Set.forEach
<anonymous>
Object.performReactRefresh
node_modules/react-refresh/cjs/react-refresh-runtime.development.js (293:0)
eval
node_modules/@next/react-refresh-utils/internal/helpers.js (124:0)

解决方法

此问题已解决。经过数小时的研究和尝试。自从我重构了对NextJs的React应用程序以来,我仍然与父目录中的旧应用程序共享一个文件。我将所有文件移到同一目录中,现在可以正常工作了。可是愚蠢的! :)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?