繁体   English   中英

Redux state 更新,但组件 state 与第一次相比没有变化

[英]Redux state updates but component state not changing from first time

我正在使用 Redux、Hooks 和 Axios 开发登录/注册系统,该操作应该获取后端并返回 session 尝试在我的会话中更新它之后的第一个组件。 is {} empty 'The initial state of session' is consoled the second time it is updated, I checked my redux state and everything works good and the state is updated from the first time so not a redux issue.The problem is in my component因为我需要它等待 Redux 完成然后 console.log(),所以我尝试 setTime() 但它等待给定时间,然后它再次控制台初始 state {}。

我的代码:

组件:问题出在 Redirect() function

import { LoginAction } from "../../Redux/Actions";
import { useForm } from "react-hook-form";
import { connect } from "react-redux";

const Login = (props) => {
  let history = useHistory();
  const alert = useAlert();

  const { handleSubmit, register, errors } = useForm();

  const onSubmit = (data) => {
    const userData = {
      username: data.username.toUpperCase(),
      password: data.password,
    };
    props.login(userData);
    setTimeout(1000, Redirect());
  };
  const Redirect = () => {
    if (props.session.user) {
      console.log(props.session);
      sessionStorage.setItem("storedSession", props.session.user.username);
      history.push("/dashboard");
    } else {
      alert.show(<div style={{ size: "10px" }}>{props.session.error}</div>);
    }
  };
  return (
    <div className="login">
      <div className="login-form">
        <h3 className="title">Sign In</h3>
        <form onSubmit={handleSubmit(onSubmit)}>
          <input
            type="text"
            placeholder="Enter your username"
            name="username"
            id="username"
            ref={register({ required: true })}
          />
          {errors.username && errors.username.type === "required" && (
            <p className="error-before-submit">This is required</p>
          )}
          <input
            id="password"
            placeholder="Enter your password"
            name="password"
            type="password"
            ref={register({ required: true })}
          />
          {errors.password && errors.password.type === "required" && (
            <p className="error-before-submit">This is required</p>
          )}
          <input
            className="btn"
            type="submit"
            ref={register({ required: true })}
          />
          <a href="/register" className="register-link">
            Create an account
          </a>
        </form>
      </div>
    </div>
  );
};
const mapStateToProps = (state) => ({
  session: state.Session,
});
const mapDispatchToProps = (dispatch) => ({
  login: (user) => dispatch(LoginAction(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Login);

减速器:


const initialState = {
  Session: {},
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case Register:
      return {
        ...state,
        Session: action.payload,
      };
    case Login:
      return {
        ...state,
        Session: action.payload,
      };
    default:
      return state;
  }
};
export default rootReducer;

行动:

export function LoginAction(user) {
  return (dispatch) => {
    Axios.post(
      "/api/login",
      {
        username: user.username,
        password: user.password,
      },
      {
        headers: { "Access-Control-Allow-Origin": "*" },
        withCredentials: true,
        crossdomain: true,
      }
    ).then((res) => {
      dispatch({
        type: Login,
        payload: res.data,
      });
    });
  };
}

如何让我的组件从第一次点击获取更新的 state 而不是初始的 state?

您可以利用useEffect挂钩而不是使用timeout

const {session} = props;

useEffect(()=>{ 

  Redirect()

},[session])

暂无
暂无

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

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