如何根据控制台响应显示警报? ReactJS

问题描述 投票:0回答:1

我在网站上注册了帐户,我希望页面根据创建帐户的成功/失败显示警报。

这是我当前的代码(我当前始终显示警报)

const isNotEmpty = (value) => value.trim() !== '';
const isEmail = (value) => value.includes('@');

function Register(props) {
    const navigate = useNavigate()

    //username input
    const {
        value: usernameValue,
        isValid: usernameIsValid,
        hasError: usernameHasError,
        valueChangeHandler: usernameChangeHandler,
        inputBlurHandler: usernameBlurHandler,
        reset: resetUsername
    } = useInput(isNotEmpty)

    //password input
    const {
        value: passwordValue,
        isValid: passwordIsValid,
        hasError: passwordHasError,
        valueChangeHandler: passwordChangeHandler,
        inputBlurHandler: passwordBlurHandler,
        reset: resetPassword
    } = useInput(isNotEmpty)

    //email input
    const {
        value: emailValue,
        isValid: emailIsValid,
        hasError: emailHasError,
        valueChangeHandler: emailChangeHandler,
        inputBlurHandler: emailBlurHandler,
        reset: resetEmail
    } = useInput(isEmail)

    let formIsValid = false
    if (usernameIsValid && emailIsValid && passwordIsValid) {
        formIsValid = true
    }

    const submitHandler = async event => {
        event.preventDefault()

        const registerInput = {
            username: usernameValue,
            email: emailValue,
            password: passwordValue
        }

        try {
            const res = await axios.post("/api/auth/register", registerInput)
            console.log(registerInput)
        } catch (error) {
            console.log(error.response?.data)
        }

        if (!formIsValid) return

        resetEmail()
        resetUsername()
        resetPassword()
        navigate()



    }


    const emailClasses = emailHasError ? 'form-control invalid' : 'form-control'
    const usernameClasses = usernameHasError ? 'form-control invalid' : 'form-control'
    const passwordClasses = passwordHasError ? 'form-control invalid' : 'form-control'

    return (
        <div className='centered'>
            <form onSubmit={submitHandler} className='register-box'>
                <h3 className="register-title">Create New Account</h3>
                <div className='control-group'>
                    <div className={emailClasses}>
                        <input required
                            type="email"
                            name="email"
                            value={emailValue}
                            placeholder='Email'
                            onChange={emailChangeHandler}
                            onBlur={emailBlurHandler}
                        />
                        {emailHasError && <p className="error-text">Please provide a valid Email</p>}
                    </div>
                    <div className={usernameClasses}>
                        <input required
                            type="text"
                            name="username"
                            value={usernameValue}
                            placeholder='Login ID'
                            onChange={usernameChangeHandler}
                            onBlur={usernameBlurHandler}
                        />
                        {usernameHasError && <p className="error-text">Please enter your future Login ID</p>}
                    </div>
                    <div className={passwordClasses}>
                        <input required
                            type="password"
                            name="password"
                            value={passwordValue}
                            placeholder='Password'
                            onChange={passwordChangeHandler}
                            onBlur={passwordBlurHandler}
                        />
                        {passwordHasError && <p className="error-text">Please enter your future Password</p>}
                    </div>
                </div>

                <Button disabled={!formIsValid}
                    onClick={alertClicked}
                    variant="primary"
                    type='submit'>
                    Create New Account
                </Button>

                <br></br>
                <br></br>

                <Alert variant="success">Account ceation was successful.</Alert>
                <Alert variant="danger">Account creation has failed.</Alert>

            </form>
        </div>
    )
}

export default Register

我之前问过类似的问题,虽然我得到了暂时解决问题的答案(通过制作两个页面并根据注册结果将用户重定向到每个页面),但这并不完全是我想要的有。

javascript reactjs node.js bootstrap-4 user-accounts
1个回答
0
投票

有多种方法可以实现这一目标。您可以在导航到主页之前添加超时并根据 API 响应显示警报,但这对用户来说并不是一个好的体验。

相反,您可以使用 react-toastify 库以更优雅的方式显示成功/错误消息,而不让用户等待。即使您重定向到另一个页面,React-toastify 也会在屏幕上显示该消息。这是逻辑,您可以根据您的要求自定义弹出窗口

定义一个新函数:

const showToast = (type, message) => {
      if (type === "success") {
        toast.success(message, {
          position: "bottom-right",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: false,
          pauseOnHover: false,
          draggable: false,
        });
      } else {
        toast.error(message, {
          position: "bottom-right",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: false,
          pauseOnHover: false,
          draggable: false,
        });
      }
    };

try {
  const res = await axios.post("/api/auth/register", registerInput)
  if(res.status === 200)
    showToast("success", "Registration successful");
  else
    showToast("error", "There seems to be an Error during registration");        
  } catch (error) {
    showToast("error", error.response?.data || "There seems to be an Error during registration");        
  }

附注在顶部的 JSX 中添加

<ToastContainer />

return (
        <div className='centered'>
        <ToastContainer />
------
© www.soinside.com 2019 - 2024. All rights reserved.