значения в handleSubmit () показывают undefined в журнале консоли - PullRequest
0 голосов
/ 09 июля 2020

Тот же код хорошо работал на предыдущей машине.

Теперь по какой-то причине значения в консоли (в handleSubmit ()) показывают undefined для электронной почты, fullName и пароля, а затем доходит до блока catch, говорящего что-то пошло не так! Помогите. У меня есть форма регистрации:

export default function MerchantCreateAccountForm() {

В ней определены такие константы, как адрес электронной почты, пароль и имя:

 // set error messages to display to the user
  const [nameError, setNameError] = useState(null);
  const [emailError, setEmailError] = useState(null);
  const [passwordError, setPasswordError] = useState(null);

  // set initial state value(s)
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [errors, setErrors] = useState({});

  const authContext = useContext(AuthContext);

В основном, НУЖНА ЗДЕСЬ ПОМОЩЬ ДЛЯ НЕОПРЕДЕЛЕННЫХ ЗНАЧЕНИЙ ДЛЯ электронной почты , fullName И пароль в handleSubmit () Позже он достигает блока catch (что-то пошло не так), но это может быть другой проблемой.

Вот функция:

  const handleSubmit = (e) => {

    try {
      e.preventDefault();
console.log("email is: " +email); //showing undefined in console. HELP
console.log("name is: "+fullName); //showing undefined in console. HELP
console.log("password is: "+password); //showing undefined in console. HELP
      const merchantSignupData =
      {
        data:
        {
          name: fullName,
          email: email,
          password: password,
          client_id: 'testclient',
          client_secret: 'testpass'
        },
        type: 'POST',
        url: 'merchant-signup',
        success: authContext.merchantSignupSuccess,
        error: authContext.networkError
      };
      merchantSignupObject.fullName, merchantSignupObject.password);
      authContext.merchantSignup(merchantSignupData);
    }
    catch{
      console.log("something went wrong!");
      //need to add error handling here
    }

  }

У меня есть хотя здесь используются проверки, которые работают нормально, на всякий случай, если это может помешать настройке данных:

  // for every change in our state this will be fired
  // we add validation here and disable the save button if required
  useEffect(() => {

    // we want to skip validation on first render
    if (firstRender.current) {
      firstRender.current = false
      return
    }

    // here we can disable/enable the save button by wrapping the setState function
    // in a call to the validation function which returns true/false
    //setDisabled(formValidation())
    formValidation();
  }, [fullName, password]) // any state variable(s) included in here will trigger the effect to run

  // here we run any validation, returning true/false
  const formValidation = () => {
    let newErrors = {}
    var error = false;

    if (fullName === "") {
      newErrors.fullName = 'Name cant be blank!'
    }
    if (email === "") {
      newErrors.email = 'Email cant be blank!'
    }
    if (!(/.+@.+\.[A-Za-z]+$/.test(email))) {
      newErrors.email = 'Enter a valid email id';
    }
    if (!(/(?=.{7,255}$)(?=.*[A-Z])(?=.*[a-z])(?=.*\d)/.test(password))) {
      newErrors.password = 'Invalid Password Format';
    }

    setNameError(errors.name)
    setEmailError(errors.email)
    setPasswordError(errors.password)
    

    if (errors != null) {
      //alert("reached")
      setErrors(newErrors);
      // $("#signup-submit").addremoveAttr("disabled") 
    }

    else {
      alert("reached here")
      setNameError(errors.fullName)
      setEmailError(errors.email)
      setPasswordError(errors.password)
      //  $("#signup-submit").removeAttr("disabled") 
    }
  }

  const showError = () => {
    alert('error!');
  }

И вот моя основная форма:

 return (
    <form onSubmit={handleSubmit()}>

      <div className="row">
        <div className="col-md-4 col-sm-6 col-xs-12">
          <div className="signup">
            <h3>{lang.merchant_signup_create_account}</h3>
            <p>{lang.merchant_signup_account_already}<a href="/linktologinpagecomponentlatertodo">{lang.merchant_signup_sign_in}</a></p>
            <div className="form-group has-error">
              <input type="text" required="required" name="fullName"
                value={fullName}
                placeholder={lang.merchant_signup_name_placeholder}
                onChange={e => setFullName(e.target.value)} />
              <label htmlFor="input" className="control-label">{lang.merchant_signup_name}</label>
              <i className="bar"></i>
              <div className="error">
                <div className="error-msg" role="alert">
                  {errors.fullName && <p>{errors.fullName}</p>}
                </div>
              </div>
            </div>
            <div className="form-group">
              <input type="text" required="required"
                placeholder={lang.merchant_signup_email_placeholder} onChange={e => setEmail(e.target.value)} />
              <label htmlFor="E-mail" className="control-label">{lang.merchant_signup_email}</label><i className="bar"></i>
              <div className="error">
                <div className="error-msg" role="alert">
                  {errors.email && <p>{errors.email}</p>}
                </div>
              </div>
            </div>
            <div className="form-group">
              <input type="password" required="required" placeholder={lang.merchant_signup_password_placeholder} onChange={e => setPassword(e.target.value)} />
              <label htmlFor="Password" className="control-label">{lang.merchant_signup_password}</label><i className="bar"></i>
              <div className="error">
                <div className="error-msg" role="alert">
                  {errors.password && <p>{errors.password}</p>}
                </div>
              </div>
              <ul className="p-suggest">
                <li> {lang.merchant_signup_password_validation1}</li>
                <li>{lang.merchant_signup_password_validation2}</li>
              </ul>
              <ul className="p-suggest">
                <li>{lang.merchant_signup_password_validation3}</li>
                <li>{lang.merchant_signup_password_validation4}</li>
              </ul>
            </div>
            <p>{lang.merchant_signup_create_terms_warning}<a target="_blank" href="#">{lang.merchant_terms_condition}</a>.</p>
          </div>
          <ul className="list-inline">
            {/* onClick={() => handleSubmit()} */},
              <li><button type="submit" id="signup-submit" className="btn btn-danger create-account next-step">{lang.merchant_signup_create_account_btn}</button></li>
          </ul>
        </div>
        <div className="col-md-8 col-sm-6 col-xs-12">
          <img className="img-responsive" src={storeImg} />
        </div>
      </div>

    </form>
  )
}

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Как вы можете прочитать, здесь ,

Убедитесь, что вы не вызываете функцию при передаче ее компоненту:

Итак, измените форму вызова метода onSubmit на

<form onSubmit={handleSubmit}>

или

<form onSubmit={() => handleSubmit()}>
0 голосов
/ 09 июля 2020

Возвращаясь к основам, глупое решение: значение атрибута отсутствует в каждом вводе, и отныне оно принимало значение как неопределенное, как показано ниже:

 <input value={password} type="password" required="required" placeholder={lang.merchant_signup_password_placeholder} onChange={e => setPassword(e.target.value)} />
...