无法在反应组件中显示错误信息。

我想显示错误信息,如 Incorrect password 当用户输入错误的密码时,作为一个警告或祝酒词。

screenshot when checkForLoginError function gets called

所以,这就是我在控制台中得到的错误。在 checkForLoginError 功能 this.props.auth.authError 第一次为空。这就是为什么我得到这个错误。而要真正显示这个信息 Incorrect password我不得不再次点击提交按钮,正如你在截图中看到的那样。


下面是代码。

登录用户控制器

 loginUser: async (req, res, next) => {
    try {
      console.log("inside login controller")
      const { email, password } = req.body
      if (!email || !password) {
        return res.status(400).json({ message: "Email and password are must" })
      }
      if (!validator.isEmail(email)) {
        return res.status(400).json({ message: "Invalid email" })
      }
      const user = await User.findOne({ email })
      if (!user) {
        return res.status(404).json({ message: "This email does not exist" })
      }
      if (!user.confirmPassword(password)) {
        // console.log("Password in login controller", password)
        return res.status(401).json({ message: "Incorrect password" })
      }

      res.status(200).json({ user })
    } catch (error) {
      return next(error)
    }
  }

登录.js

mport React, { Component } from "react"
import validator from "validator"
import { loginUser } from "../actions/userActions"
import { connect } from "react-redux"
import { Link } from "react-router-dom"
import { toastError } from "../../utils/toastify"

class LoginForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      email: "",
      password: "",
    }
  }

  handleChange = (event) => {
    const { name, value } = event.target
    this.setState({
      [name]: value,
    })
  }



  checkForLoginError = () => {
    console.log("inside checkForLoginError")
    console.log(this.props.auth.authError)
    if (this.props.auth.authError !== null) {
      const authError = this.props.auth.authError.response.data.message
      console.log(authError)
      if (authError === null) {
        this.props.history.push("/")
      } else {
        return toastError(authError)
      }
    }
  }

  handleSubmit = (event) => {
    event.preventDefault()
    const { email, password } = this.state

    const loginData = {
      email: this.state.email,
      password: this.state.password,
    }

    if (!email || !password) {
      return toastError("Email and password are must.")
    }

    if (password.length < 6) {
      return toastError("Password must contain 6 characters.")
    }

    if (!validator.isEmail(email)) {
      return toastError("Invalid email.")
    }

    this.props.dispatch(loginUser(loginData, this.checkForLoginError()))
  }

  render() {
    const isAuthInProgress = this.props.auth.isAuthInProgress
    return (
      <div>
        <div className="field">
          <p className="control has-icons-left has-icons-right">
            <input
              className="input"
              onChange={this.handleChange}
              name="email"
              value={this.state.email}
              type="email"
              placeholder="Email"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-envelope"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <p className="control has-icons-left">
            <input
              className="input"
              onChange={this.handleChange}
              name="password"
              value={this.state.password}
              type="password"
              placeholder="Password"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-lock"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <p className=Also, is there a need for similar checks like I have done both in controller and the component like `if (!email || !password)` and `if (!validator.isEmail(email))`. Or should it be only in the backend?
"control">
            {isAuthInProgress ? (
              <button className="button is-success is-loading">Login</button>
            ) : (
              <button onClick={this.handleSubmit} className="button is-success">
                Login
              </button>
            )}
          </p>
        </div>
        <Link to="/forgot-password">
          <p className="has-text-danger">Forgot password?</p>
        </Link>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return state
}

export default connect(mapStateToProps)(LoginForm)

登录用户动作创建者

export const loginUser = (loginData, redirect) => {
  return async (dispatch) => {
    dispatch({ type: "AUTH_STARTS" })
    try {
      const res = await axios.post(`${baseUrl}/users/login`, loginData)
      console.log(res.data)
      dispatch({
        type: "AUTH_SUCCESS",
        data: { user: res.data.user }
      })
      localStorage.setItem("authToken", res.data.token)
      redirect()
      toastSuccess("You are now logged in!")
    } catch (error) {
      console.log
      dispatch({
        type: "AUTH_ERROR",
        data: { error },
      })
    }
  }
}

减速器

const auth = (state = initialState, action) => {
  switch (action.type) {
    case "AUTH_STARTS":
      return {
        ...state,
        isAuthInProgress: true,
        isAuthenticated: false,
        authError: null,
      }

    case "AUTH_SUCCESS":
      return {
        ...state,
        isAuthInProgress: false,
        authError: null,
        isAuthenticated: true,
        isIdentifyingToken: false,
        user: action.data.user,
      }

    case "AUTH_ERROR":
      return {
        ...state,
        isAuthInProgress: false,
        authError: action.data.error,
        isAuthenticated: false,
        user: {},
      }

解决方案:

就我理解你的问法,我给出了我的意见。如果它不是你正在寻求的,请忽略。

当你在checkForLoginError中得到401未经授权的错误时,你可以通过this.props.history.push(”)重定向用户,而不是通过this.props.history.push(”)来重定向用户,你可以在authError=true的条件下返回一个Modeal,这将显示不正确的密码。

在点击上面的Modal按钮时,你可以使用this.props.history.push(”)重定向用户。

本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/3939.html

(0)
上一篇 2022年6月29日 下午4:37
下一篇 2022年6月29日 下午4:37

相关推荐

发表评论

登录后才能评论