无法在ReactJS登录页面中获取更新状态

问题描述

我是React JS的新手,并且一直遇到问题。我正在构建一个登录页面,当用户输入无效的凭据时,我想在其中显示一些错误。输入正确的凭据时,我可以登录,但是输入无效的凭据时,也可以登录。在调试时,我发现在mapPropsToState中虽然我将isLoggedIn参数设置为false,但未将其映射到道具。道具在这里仍然是正确的。 我的登录页面

const required = (value) => {
  if (!value) {
    return (
      <div className="alert alert-danger" role="alert">
        This field is required!
      </div>
    );
  }
};

const Login = (props) => {
  const form = useRef();
  const checkBtn = useRef();

  const [username,setUsername] = useState("");
  const [password,setPassword] = useState("");
  const [loading,setLoading] = useState(false);

  const { isLoggedIn } = useSelector(state => state.auth);
  const { message } = useSelector(state => state.message);

  const dispatch = usedispatch();

  const onChangeUsername = (e) => {
    const username = e.target.value;
    setUsername(username);
  };

  const onChangePassword = (e) => {
    const password = e.target.value;
    setPassword(password);
  };

  const handleLogin = (e) => {
    e.preventDefault();
    setLoading(true);
    form.current.validateall();
    if (checkBtn.current.context._errors.length === 0) {
      dispatch(login(username,password))
        .then(() => {
          if (props !=null && props.isAuthenticated) {
            props.history.push("/home");
          }
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      setLoading(false);
    }
  };

  if (isLoggedIn) {
    // return <Redirect to="/home" />;
  }

  return (
    <div className="col-md-12">
      <div className="card card-container">
        <img
          src="//ssl.gstatic.com/accounts/ui/avatar_2x.png"
          alt="profile-img"
          className="profile-img-card"
        />

        <Form onSubmit={handleLogin} ref={form}>
          <div className="form-group">
            <label htmlFor="username">Username</label>
            <Input
              type="text"
              className="form-control"
              name="username"
              value={username}
              onChange={onChangeUsername}
              validations={[required]}
            />
          </div>

          <div className="form-group">
            <label htmlFor="password">Password</label>
            <Input
              type="password"
              className="form-control"
              name="password"
              value={password}
              onChange={onChangePassword}
              validations={[required]}
            />
          </div>

          <div className="form-group">
            <button className="btn btn-primary btn-block" disabled={loading}>
              {loading && (
                <span className="spinner-border spinner-border-sm"></span>
              )}
              <span>Login</span>
            </button>
          </div>

          {message && (
            <div className="form-group">
              <div className="alert alert-danger" role="alert">
                {message}
              </div>
            </div>
          )}
          <CheckButton style={{ display: "none" }} ref={checkBtn} />
        </Form>
      </div>
    </div>
  );
};
Login.propTypes = {
  login: PropTypes.func.isrequired,isAuthenticated: PropTypes.bool.isrequired
}
const mapStatetoProps = (state) => ({
  isAuthenticated: state.auth.isLoggedIn
})
export default connect(mapStatetoProps,{ login })(Login);

我的登录和注销功能正在起作用:

    export const login = (username,password) => (dispatch) => {
  return AuthServicee.login(username,password).then(
    (data) => {
      if(data.success) {
        userService.getUserDetails(username).then((data) => {
          localStorage.setItem("user",JSON.stringify(data.data));
          dispatch({
            type: LOGIN_SUCCESS,payload: { user: data },});
          return Promise.resolve();
        },(error) => {
          const message =
          (error.response &&
            error.response.data &&
            error.response.data.message) ||
          error.message ||
          error.toString();
  
          dispatch({
            type: LOGIN_FAIL,});
  
          dispatch({
            type: SET_MESSAGE,payload: message,});
  
          return Promise.reject();
        }).catch(err => {
          dispatch({
            type: LOGIN_FAIL,});
        });;   
      } else {
        dispatch({
          type: LOGIN_FAIL,});
        dispatch({
          type: SET_MESSAGE,payload: data.error,});
      }
    },(error) => {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();

      dispatch({
        type: LOGIN_FAIL,});

      dispatch({
        type: SET_MESSAGE,});

      return Promise.reject();
    }
  );
};

export const logout = () => (dispatch) => {
  AuthServicee.logout();

  dispatch({
    type: logoUT,});
};

减速器类:

    const user = JSON.parse(localStorage.getItem("user"));

const initialState = user
  ? { isLoggedIn: true,user }
  : { isLoggedIn: false,user: null };

export default function (state = initialState,action) {
  const { type,payload } = action;

  switch (type) {
    case LOGIN_SUCCESS:
      return {
        ...state,isLoggedIn: true,user: payload.user,};
    case LOGIN_FAIL:
      return {
        ...state,isLoggedIn: false,user: null,};
    case logoUT:
      return {
        ...state,};
    default:
      return state;
  }
}

有人可以在这里帮助我吗?

编辑:我在mapStatetoProps的状态变量中获得了正确的值,但是以某种方式尝试在调度调用的then函数中使用它时,仍然会获得props.isAuthenticated为true。尽管我应该在mapStatetoProps中更新它,但它应该已经变成了假。

解决方法

如果将您重定向到/home,我将首先检查您的验证功能,因为正如您所说的,传递无效值。如果输入form.current.validateAll();无效,此功能会做什么?