Apakah penyelesaian untuk membentuk isu pengesahan dalam React JSX?
P粉094351878
P粉094351878 2024-04-03 11:53:49
0
1
329

Saya cuba membuat borang pengesahan dalam React tetapi sejak saya menambah menyimpan data pendaftaran pengguna, saya menghadapi banyak isu.

import React, { useState } from "react";
import "./registerstyle.css";
import EyeIcon from "./EyeIcon.png";
import EyeIconHide from "./EyeIconHide.png";
import { signup } from "../../api/client";

function RegisterPage() {
  const [showPassword, setShowPassword] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
  const [nameEmpty, setNameEmpty] = useState(false);
  const [confirmPasswordEmpty, setconfirmPasswordEmpty] = useState(false);
  const [emailEmpty, setEmailEmpty] = useState(false);
  const [passwordEmpty, setPasswordEmpty] = useState(false);
  const [newsletter, setNewsletter] = useState(false); // Aggiunto lo stato per la checkbox

  const [name, setName] = useState(null);
  const [email, setEmail] = useState(null);
  const [password, setPassword] = useState(null);
  const [cpass, setCpass] = useState(null);
  const user = { name: name, email: email, password: password, cpass: cpass };



  const handleShowPassword = () => {
    setShowPassword(!showPassword);
    setPasswordVisible(!passwordVisible);
  };

  const handleShowConfirmPassword = () => {
    setShowConfirmPassword(!showConfirmPassword);
    setConfirmPasswordVisible(!confirmPasswordVisible);
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();

    // Verifica se i campi email e password sono vuoti
    if (!e.target.email.value) {
      setEmailEmpty(true);
      console.log("email True");
    } else {
      setEmailEmpty(false);
      console.log("email False");
    }

    if (!e.target.name.value) {
      setNameEmpty(true);
    } else {
      setNameEmpty(false);
    }

    if (!e.target.password.value) {
      setPasswordEmpty(true);
    } else {
      setPasswordEmpty(false);
    }

    if (!e.target.confirmPassword.value) {
      setconfirmPasswordEmpty(true);
    } else {
      setconfirmPasswordEmpty(false);
    }
  };

  const handleNewsletterChange = (e) => {
    setNewsletter(e.target.checked);
  }; // Funzione per gestire il cambiamento di stato della checkbox

  const passwordInputClass = passwordVisible ? "passwordVisible" : "";
  const confirmPasswordInputClass = confirmPasswordVisible ? "confirmPasswordVisible" : "";

  return (
    <div className="backgroundRegister">
      <div className="titleRegister" />
      <div className="breakRegister" />
      <div className="contlogRegister" />
      <div className="signIn" />
      <form className="formRegister" onSubmit={handleFormSubmit}>
        <label>
          {/* NAME */}
          <input type="text" name="name" placeholder="Name" onChange={(e) => { setName(e.target.value) }} required/>
        </label>
        {nameEmpty && (
          <div>
            <div className="alertCircleName" />
            <div className="FillThisName" />
            <div className="RedRectangleName" />
            <div className="nameError" />
          </div>
        )}
        <br />
        <label>
          {/* EMAIL */}
          <input type="email" name="email" placeholder="Email" onChange={(e) => { setEmail(e.target.value) }} required/>
        </label>
        {emailEmpty && (
          <div>
            <div className="alertCircleEmailRegister" />
            <div className="FillThisEmailRegister" />
            <div className="RedRectangleEmailRegister" />
            <div className="emailErrorRegister" />
          </div>
        )}
        <br />
        <label>
          {/* PASSWORD*/}
          <input
            type={showPassword ? "text" : "password"}
            name="password"
            placeholder="Password"
            className={passwordInputClass}
            onChange={(e) => { setPassword(e.target.value) }}
          />
          <img
            src={passwordVisible ? EyeIconHide : EyeIcon}
            alt="eye-icon"
            className="eyeIconRegister1"
            onClick={() => {
              handleShowPassword();
            }}
          />
        </label>
        {passwordEmpty && (
          <div>
            <div className="alertCirclePasswordRegister" />
            <div className="FillThisPasswordRegister" />
            <div className="RedRectanglePasswordRegister" />
            <div className="passwordErrorRegister" />
          </div>
        )}
        <br />
        <label>
          {/* CONFIRM PASSWORD */}
          <input
            type={showConfirmPassword ? "text" : "password"}
            name="confirmPassword"
            placeholder="Confirm Password"
            className={confirmPasswordInputClass}
            onChange={(e) => { setCpass(e.target.value) }}
          />
          <img
            src={confirmPasswordVisible ? EyeIconHide : EyeIcon}
            alt="eye-icon"
            className="eyeIconRegister2"
            onClick={() => {
              handleShowConfirmPassword();
            }}
          />
        </label>
        {confirmPasswordEmpty && (
          <div>
            <div className="alertCircleConfirmPassword" />
            <div className="FillThisConfirmPassword" />
            <div className="RedRectangleConfirmPassword" />
            <div className="confirmPasswordError" />
          </div>
        )}
        <br />
        <label> {/* NEWSLETTER */}
          <input type="checkbox" name="newsletter" checked={newsletter} onChange={handleNewsletterChange} />
        </label>
        <span className="newsletter">Send me newsletters, tricks and updates. </span>
        <br />
        <input type="submit" value="SIGN IN" className="signInButton" onClick={(e) => {
          e.preventDefault();
          signup(user);
          handleFormSubmit(e);
        }}/>
      </form>
      <div className="registerSign">
        Already have an account? <a href="" className="colorRegister">Login now</a>
      </div>
    </div>

  );
}

export default RegisterPage;

Ini adalah kod pendaftaran:

import axios from "axios";

// const client = axios.create({
//   baseURL: "http://localhost:9000", // o l'endpoint del vostro backend
//   headers: {
//     "Content-Type": "application/json",
//     //     "Authorization": "Bearer " + localStorage.getItem("token")
//   }
// });

// export default client;


async function signup(user) {
  const newUser = JSON.stringify(user);
  console.log("sono dentro la funzione");

  try {
    return await axios.post("http://localhost:3000/signup", newUser);
  } catch (err) {
    if (err.response) {
      return err.response.data;
    } else {
      console.log("Errore:", err.message);
    }
  }
};

async function login(user) {
  const newUser = JSON.stringify(user);
  console.log("sono dentro");

  try {
    return await axios.post("http://localhost:3000/login", newUser);
    //return await axios.post("http://localhost:3000/login",)
  } catch (err) {
    if (err.response) {
      return err.response.data;
    } else {
      console.log("Errore:", err.message);
    }
  }
};

async function loginOld(credentials) {
  const loginData = JSON.stringify(credentials);
  await axios.post("http://localhost:3000/login", loginData);
};

export { signup, login };

Apa yang saya jangka akan berlaku, apabila medan dibiarkan kosong apabila anda mengklik butang, ia akan muncul daripada imej yang saya buat untuk membulatkan medan yang dibiarkan kosong. Kadangkala ia memberikan ralat seperti ini:

TypeError: Cannot read properties of undefined (reading 'value')
    at handleFormSubmit (http://localhost:3000/main.7b4752724621de0f0bc6.hot-update.js:66:25)
    at onClick (http://localhost:3000/main.7b4752724621de0f0bc6.hot-update.js:387:11)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:14655:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:14699:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:14756:35)
    at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/bundle.js:14770:29)
    at executeDispatch (http://localhost:3000/static/js/bundle.js:18914:7)
    at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/bundle.js:18940:11)
    at processDispatchQueue (http://localhost:3000/static/js/bundle.js:18951:9)
    at dispatchEventsForPlugins (http://localhost:3000/static/js/bundle.js:18960:7)```

I'm desperate and don't really know where to put my hands.

P粉094351878
P粉094351878

membalas semua(1)
P粉833546953

Memandangkan anda mengawal keadaan setiap input, anda tidak perlu mendapatkan nilai yang diserahkan (walaupun cara anda cuba melakukannya tidak berkesan). Sebaliknya, gunakan nilai terkawal dalam panggilan balik komit:

const handleFormSubmit = (e) => {
  e.preventDefault();

  // Verifica se i campi email e password sono vuoti
  if (!email) {
    setEmailEmpty(true);
    console.log("email True");
  } else {
    setEmailEmpty(false);
    console.log("email False");
  }

  if (!name) {
    setNameEmpty(true);
  } else {
    setNameEmpty(false);
  }

  if (!password) {
    setPasswordEmpty(true);
  } else {
    setPasswordEmpty(false);
  }

  if (!confirmPassword) {
    setconfirmPasswordEmpty(true);
  } else {
    setconfirmPasswordEmpty(false);
  }
};
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!