0

我有一个客户报告说,当他们使用 NPM 构建 React 应用程序时,他们在附加的屏幕截图中收到错误。“钩子只能在函数体内调用”。屏幕截图显示了错误,但对我来说毫无意义,当我运行相同的代码(相同的项目)时,我没有收到错误。我正在粘贴下面的完整代码,但您可以看到它与错误中的相同。我们都运行相同版本的 NPM。

来自 eslint 的错误截图

    import React, { useState, useEffect } from "react";
    import "react-toastify/dist/ReactToastify.css";
    import { ToastContainer, toast } from "react-toastify";

    const SignMeUp = ({ signupCallback }) => {
      useEffect(() => {
        console.log(`SignMeUp:useEffect called`);
      });

      const [email, setEmail] = useState();
      const [emailValid, setEmailValid] = useState(false);
      const [sendProcessing, setSendProcessing] = useState(false);

      function validateEmail(email) {
        const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
      }

      const notify = () => {
        toast.info(`You will be notified of upcoming events ${email}`);
      };

      function sendEmailToBackend() {
        setSendProcessing(true);
        new Promise(function(resolve) {
          setTimeout(function() {
            setSendProcessing(false);
            setEmail("");
            resolve();
          }, 1000);
        }).then(() => {
          notify();
          signupCallback(email);
          setEmail("");
        });
      }

      const buttonText = sendProcessing ? "processing..." : "Get Updates";

      //console.log("src/SignMeUp called");

      return (
        <div className="container">
          <div>
            <ToastContainer />
            <div className="content">
              <input
                value={email}
                onChange={e => {
                  setEmailValid(validateEmail(e.target.value));
                  return setEmail(e.target.value);
                }}
                placeholder="Enter Email"
                type="email"
                name="email"
                required
                required
              />
              &nbsp;
              <button
                disabled={!emailValid || sendProcessing}
                className="btn"
                onClick={sendEmailToBackend}
                type="submit"
              >
                {buttonText}
              </button>
            </div>
          </div>
        </div>
      );
    };

    export default SignMeUp;
4

0 回答 0