【问题标题】:dispatching two actions one after the other in react asyncronously在异步反应中一个接一个地调度两个动作
【发布时间】:2021-07-10 20:29:00
【问题描述】:

我一个接一个地分派两个动作,其中第二个分派使用第一个分派的减速器,但我变得不确定,因为第二个动作在第一个动作被分派之前被分派。

这是我的代码:

const auth = useSelector((state) => state.auth);
const student = useSelector((state) => state.student);

useEffect(() => {
    const id = auth.user.user;
    dispatch(getStudent(id));
  }, [auth.authenticate]);

if (auth.authenticate) {
    if (auth.user.user_type.is_student == true) {
      if (student.detail && student.detail.length > 0) {
        return <Redirect to={"/student/classes"}></Redirect>;
      } else {
        return <Redirect to={"/student/profile"}></Redirect>;
      }
    } else {
      return <Redirect to={"/faculty/classes"}></Redirect>;
    }
  }
const userLogin = (e) => {
    e.preventDefault();
    const user = {
      username,
      password,
    };
    dispatch(login(user));
    
    
  };

我试图根据是否填充 student.detail 将其重定向到页面,但它首先重定向并稍后执行 useEffect 函数。

【问题讨论】:

    标签: reactjs redux react-redux dispatch


    【解决方案1】:
    useEffect(() => {
    if(auth && auth.user && student.detail.length == 0) {
      const id= auth.user.user
      console.log(id)
      dispatch(getStudent(id));
    }, [auth]);
    

    一旦商店中的 auth 状态更新,就调度第二个操作,以便您将 git 获取所需的用户 ID。

    或者

    使用异步/等待。

    【讨论】:

    • 嘿,谢谢您的回复,但我也尝试根据学生详细信息是否填充将其重定向到不同的页面。我已经编辑了我的问题,以包含它的代码。你能看看吗?
    猜你喜欢
    • 2020-07-17
    • 2020-11-15
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2019-12-24
    • 2022-06-29
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多