简体   繁体   English

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

[英]Unable to get the updated state in ReactJS login page

I am new to React JS and have stuck on a problem.我是 React JS 的新手并且遇到了一个问题。 I am building a login page where I want to display some error when the user enters invalid credentials.我正在构建一个登录页面,当用户输入无效凭据时,我想在其中显示一些错误。 When I enter the correct credentials I am able to login but when I enter the invalid credentials then also I am able to login.当我输入正确的凭据时,我可以登录,但是当我输入无效的凭据时,我也可以登录。 On debugging I have found that in mapPropsToState although I get isLoggedIn parameter as false but it is not mapped to props.在调试时,我发现在 mapPropsToState 中虽然我得到 isLoggedIn 参数为 false 但它没有映射到道具。 props still get true here. props 在这里仍然有效。 My Login Page:我的登录页面:

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);

my login and logout function in action:我的登录和注销功能正在运行:

    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,
        payload: message,
      });

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

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

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

reducer class:减速机类:

    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,
        isLoggedIn: false,
        user: null,
      };
    default:
      return state;
  }
}

can someone please help me here?有人可以帮我吗?

Edit: I get correct values in my state variable in mapStateToProps but somehow when I try to use it in then function of my dispatch call, I still get props.isAuthenticated as true.编辑:我在 mapStateToProps 中的状态变量中获得了正确的值,但是当我尝试在我的调度调用的 then 函数中使用它时,我仍然得到 props.isAuthenticated 为真。 Although it should have become false as I have updated it in mapStateToProps.尽管我在 mapStateToProps 中更新了它,但它应该变成了错误。

If you're being redirected to the /home I would look into your validation functions first, because as you say the pass invalid values.如果您被重定向到/home我会首先查看您的验证函数,因为正如您所说,传递的值无效。 What does this function do if you have invalid inputs form.current.validateAll();如果您有无效输入form.current.validateAll();这个函数会做什么? ? ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM