首页 > 解决方案 > 为什么 Next.js 不接受传递的函数作为函数?

问题描述

在 ReactJs 中它运行良好。

在此处输入图像描述

import React, { useState, useEffect } from "react";
import { Snackbar } from "@material-ui/core";
import axios from "axios";
import { withTranslation } from "../../i18n";
import MuiAlert from "@material-ui/lab/Alert";
import sha512 from "crypto-js/sha512";
import { LoginEmailIn, LoginEmailOut } from "../../Types";
import { getTempUserUuid } from "../../util/Utility";
//import ReactPixel from "react-facebook-pixel";
import styles from "../../styles/LoginAndRegistration.module.css";
import {BEUrl} from "../../util/Utility"


function Alert(props: any) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}
function LoginWithEmail({ t },props: {
  eventId: string;
  trackUserInteractions:boolean;
  eventName: string;
  setLogin: (a:boolean)=> void;
}) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [alertOpen, setAlertOpen] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");
  const [alertType, setAlertType] = useState("error");
  const alertClose = (event: any, reason: any) => {
    if (reason === "clickaway") {
      return;
    }
    setAlertOpen(false);
  };
  const checkEmail = () => {
    const regex = /^(([^<>()[\]\\.,;:\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,}))$/;
    if (email === "") {
      setAlertType("error");
      setAlertMessage(t("Please enter your registered e-mail address"));
      setAlertOpen(true);
      return false;
    } else if (!regex.test(email)) {
      setAlertType("error");
      setAlertMessage(t("The entered e-mail address is not valid"));
      setAlertOpen(true);
      return false;
    } else return true;
  };

  const checkPassword = () => {
    if (password === "") {
      setAlertType("error");
      setAlertMessage(t("Please enter your password"));
      setAlertOpen(true);
      return false;
    } else return true;
  };

  const loginButtonPressed = () => {
    if (checkEmail() && checkPassword()) {
      const loginData: LoginEmailIn = {
        email: email,
        passwordHash: sha512(password).toString(),
        tempUserId: getTempUserUuid(),
      };
      let url = BEUrl + "loginEmail";
      axios({
        method: "post",
        url: url,
        data: loginData,
        headers: { "Content-Type": "application/json", crossDomain: true },
      })
        .then((resp: any) => {
          const data: LoginEmailOut = resp.data;
          if (!data.error) {
            setAlertType("success");
            setAlertMessage(t(`Successful login, Welcome ${data.userName!}`));
            setAlertOpen(true);
            localStorage.setItem("isRegistrationHappened", "true");
            localStorage.setItem("userNameLoggedIn", data.userName!);
            localStorage.setItem("jwt", data.jwt!);
            setTimeout(function () {
              window.location.reload();
            }, 1200);
          } else {
            setAlertType("error");
            setAlertMessage(t(`${data.error}`));
            setAlertOpen(true);
          }
        })
        .catch((error) => console.error(error));
    }
  };

  /*const trackEmailLoginFinished = () => {
    if (useClientSide) {
      if (
        window.location.hostname !== "localhost" &&
        props.trackUserInteractions &&
        !userInteractions.includes(`IA ${props.eventName} EmailLoginFinished`)
      ) {
        ReactPixel.track(`IA ${props.eventName} EmailLoginFinished`, {
          content_ids: [props.eventId],
        });
        userInteractions.push(`IA ${props.eventName} EmailLoginFinished`);
        localStorage.setItem(
          "userInteractions",
          JSON.stringify([...userInteractions])
        );
      }
    }
  };*/

  const [userInteractions, setUserInteractions] = useState();

useEffect(()=> {
  setUserInteractions(JSON.parse(
    localStorage.getItem("userInteractions") ?? "[]"
  ))
},[])

  return (
    <>
      <div className={styles.loginContainer}>
        <label className={styles.loginInputLabel}>{`${t(
          "Please enter your e-mail address"
        )}`}</label>
        <input
          id="loginMail"
          name="loginMail"
          className="loginInput toLowerCase"
          autoFocus
          type="email"
          onChange={(event) => setEmail(event.target.value.toLowerCase())}
        />
      </div>
      <label className="loginInputLabel">{`${t(
        "Please enter your password"
      )}`}</label>
      <input
        id="loginPassword"
        className="loginInput"
        name="loginPassword"
        type="password"
        onChange={(event) => setPassword(event.target.value)}
      />
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          flexDirection: "column",
        }}
      >
        <button
          className="loginAndRegButton"
          onClick={() => {
            loginButtonPressed();
            /*trackEmailLoginFinished();*/
          }}
        >
          {t("Login")}
        </button>
        <p style={{ margin: 0 }} className="loginOrRegSwitch">
          {t("You don't have an account yet")}?{" "}
          <a href="#" onClick={() => props.setLogin(false)}>
            {" "}
            {t("Sign up")}
          </a>
        </p>
      </div>
      <Snackbar open={alertOpen} autoHideDuration={3000} onClose={alertClose}>
        <Alert onClose={alertClose} severity={alertType}>
          {alertMessage}
        </Alert>
      </Snackbar>
    </>
  );
}

export default withTranslation("translate")<any>(LoginWithEmail);

标签: reactjsnext.js

解决方案


我认为它必须是:

function LoginWithEmail({ t, ...props }) { /* ... */ }

推荐阅读