首页 > 解决方案 > 在按下按钮之前反应组件触发警报以及用户输入之前的 POST 请求

问题描述

在信息输入字段之前转到页面并执行 POST 请求时显示警报。有人可以告诉我或告诉我我在这里做错了什么。提前致谢!警报和 POST 请求仅应在用户填写注册表后发生。检查电子邮件和密码是否匹配时发生的警报。之后,应该发生 POST 请求并通过 API 将其保存到数据库中。

import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import uuid from 'react-uuid';

export default function RegistrationForm() {
  const initialForm = {
    first_name: '',
    last_name: '',
    username: '',
    email: '',
    email_match: '',
    password: '',
    password_match: '',
  };
  const history = useHistory();

  const [registrationForm, setRegistrationForm] = useState({ ...initialForm });

  const handleChange = ({ target }, event) => {
    event.preventDefault();
    setRegistrationForm({ ...registrationForm, [target.name]: target.value });
  };
  useEffect(() => {
    const currentAPI = `*API*`;
    if (
      registrationForm.email === registrationForm.email_match &&
      registrationForm.password === registrationForm.password_match
    ) {
      alert(`You're Email and Password Matches!`);
      const abortController = new AbortController();
      async function postRegistration() {
        try {
          const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              registration_id: uuid(),
              username: '',
              first_name: '',
              last_name: '',
              email: '',
              password: '',
              password_match: '',
            }),
          };
          //eslint-disable-next-line
          const response = await fetch(currentAPI, requestOptions, {
            signal: abortController.signal,
          });
        } catch (error) {
          if (error.name === 'AbortError') {
            console.log('Post was not successful');
          } else {
            throw error;
          }
        }
      }
      postRegistration();
      return () => {
        abortController.abort();
      };
    } else {
      alert(`Email and Password Do Not Match!`);
    }
  }, []);
  const submitHandler = (event) => {
    event.preventDefault();
    const { first_name, last_name, username, email, password, password_match } =
      registrationForm;
    console.log(
      first_name,
      last_name,
      username,
      email,
      password,
      password_match
    );
    setRegistrationForm({ ...initialForm });
    history.push('/Login');
  };

  return (
    <div style={{ padding: '30px 0px' }}>
      <div className='p-3 rounded' style={{ border: '2px solid #42fcfc' }}>
        <div
          className='card-title'
          style={{ display: 'flex', justifyContent: 'center' }}
        >
          <h3 className='page-title'>Register</h3>
        </div>
        <form
          onSubmit={submitHandler}
          className='card-body'
          style={{ color: '#fff' }}
        >
          <label htmlFor='first_name' className='d-block'>
            First Name:
          </label>
          <input
            name='first_name'
            type='text'
            id='first_name'
            required
            onChange={handleChange}
            value={registrationForm.first_name}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='last_name' className='d-block'>
            Last Name:
          </label>
          <input
            name='last_name'
            type='text'
            id='last_name'
            required
            onChange={handleChange}
            value={registrationForm.last_name}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='username' className='d-block'>
            Username:
          </label>
          <input
            name='username'
            type='text'
            id='username'
            required
            onChange={handleChange}
            value={registrationForm.username}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='email' className='d-block'>
            Email:
          </label>
          <input
            name='email'
            type='text'
            id='email'
            required
            onChange={handleChange}
            value={registrationForm.email}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='email_match' className='d-block'>
            Confirm Email:
          </label>
          <input
            name='email_match'
            type='email'
            id='email_match'
            required
            onChange={handleChange}
            value={registrationForm.email_match}
            style={{ width: '100%' }}
          />
          <label htmlFor='password' className='d-block'>
            Password:{' '}
          </label>
          <input
            name='password'
            type='password'
            id='password'
            required
            onChange={handleChange}
            value={registrationForm.password}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='password_match' className='d-block'>
            Confirm password:
          </label>
          <input
            name='password_match'
            type='password'
            id='password_match'
            required
            onChange={handleChange}
            value={registrationForm.password_match}
            style={{ width: '100%' }}
          />
          <button type='submit' className='btn btn-primary mt-3'>
            Register
          </button>
        </form>
      </div>
    </div>
  );
}

标签: javascriptreactjs

解决方案


问题是当用户名和密码都是空字符串(包括初始状态)时,您的条件匹配。也许你想要这样的东西来确保非空字符串:

  useEffect(() => {
    const currentAPI = `*API*`;
    if (
      registrationForm.email &&
      registrationForm.email === registrationForm.email_match &&
      registrationForm.password &&
      registrationForm.password === registrationForm.password_match
    ) {
      //...
    }
  }, [registrationForm.email, registrationForm.email_match, registrationForm.password, registrationForm.password_match]);

另请注意,您应该在末尾指定依赖项useEffect,而不是空列表[][]或者,您可以省略依赖项列表,但在这种情况下您不需要。

正如上面@Nick 的评论中所提到的,当注册按钮被按下时,您最好运行此代码,useEffect完全避免,如下所示:

import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import uuid from 'react-uuid';

export default function RegistrationForm() {
  const initialForm = {
    first_name: '',
    last_name: '',
    username: '',
    email: '',
    email_match: '',
    password: '',
    password_match: '',
  };
  const history = useHistory();

  const [registrationForm, setRegistrationForm] = useState({ ...initialForm });

  const handleChange = ({ target }, event) => {
    event.preventDefault();
    setRegistrationForm({ ...registrationForm, [target.name]: target.value });
  };
  const submitHandler = (event) => {
    event.preventDefault();
    const { first_name, last_name, username, email, password, password_match } =
      registrationForm;
    console.log(
      first_name,
      last_name,
      username,
      email,
      password,
      password_match
    );
    const currentAPI = `*API*`;
    if (
      registrationForm.email &&
      registrationForm.email === registrationForm.email_match &&
      registrationForm.password &&
      registrationForm.password === registrationForm.password_match
    ) {
      alert(`You're Email and Password Matches!`);
      const abortController = new AbortController();
      async function postRegistration() {
        try {
          const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              registration_id: uuid(),
              username: '',
              first_name: '',
              last_name: '',
              email: '',
              password: '',
              password_match: '',
            }),
          };
          //eslint-disable-next-line
          const response = await fetch(currentAPI, requestOptions, {
            signal: abortController.signal,
          });
        } catch (error) {
          if (error.name === 'AbortError') {
            console.log('Post was not successful');
          } else {
            throw error;
          }
        }
      }
      postRegistration();
    } else {
      alert(`Email and Password Do Not Match!`);
    }
  }, []);
    history.push('/Login');
  };

  return (
    <div style={{ padding: '30px 0px' }}>
      <div className='p-3 rounded' style={{ border: '2px solid #42fcfc' }}>
        <div
          className='card-title'
          style={{ display: 'flex', justifyContent: 'center' }}
        >
          <h3 className='page-title'>Register</h3>
        </div>
        <form
          onSubmit={submitHandler}
          className='card-body'
          style={{ color: '#fff' }}
        >
          <label htmlFor='first_name' className='d-block'>
            First Name:
          </label>
          <input
            name='first_name'
            type='text'
            id='first_name'
            required
            onChange={handleChange}
            value={registrationForm.first_name}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='last_name' className='d-block'>
            Last Name:
          </label>
          <input
            name='last_name'
            type='text'
            id='last_name'
            required
            onChange={handleChange}
            value={registrationForm.last_name}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='username' className='d-block'>
            Username:
          </label>
          <input
            name='username'
            type='text'
            id='username'
            required
            onChange={handleChange}
            value={registrationForm.username}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='email' className='d-block'>
            Email:
          </label>
          <input
            name='email'
            type='text'
            id='email'
            required
            onChange={handleChange}
            value={registrationForm.email}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='email_match' className='d-block'>
            Confirm Email:
          </label>
          <input
            name='email_match'
            type='email'
            id='email_match'
            required
            onChange={handleChange}
            value={registrationForm.email_match}
            style={{ width: '100%' }}
          />
          <label htmlFor='password' className='d-block'>
            Password:{' '}
          </label>
          <input
            name='password'
            type='password'
            id='password'
            required
            onChange={handleChange}
            value={registrationForm.password}
            style={{ width: '100%', marginBottom: '5px' }}
          />
          <label htmlFor='password_match' className='d-block'>
            Confirm password:
          </label>
          <input
            name='password_match'
            type='password'
            id='password_match'
            required
            onChange={handleChange}
            value={registrationForm.password_match}
            style={{ width: '100%' }}
          />
          <button type='submit' className='btn btn-primary mt-3'>
            Register
          </button>
        </form>
      </div>
    </div>
  );
}

推荐阅读