【问题标题】:want to redirect to page after the action is dispatched in useEffect想要在 useEffect 中调度操作后重定向到页面
【发布时间】:2021-09-20 18:51:16
【问题描述】:

我试图根据 student.detail 是否填充来将 history.push 到页面,但似乎调度操作没有完成并且 if 块代码运行,因此它 history.push 到错误的页面。我希望它完成调度操作,填充学生减速器和执行 if 块,检查学生减速器状态然后重定向。

const auth = useSelector((state) => state.auth);
const student = useSelector((state) => state.student);
useEffect(() => {
const id = auth.user.user;
dispatch(getStudent(id));

if (auth.authenticate) {
  if (auth.user.user_type.is_student == true) {
    if (student.detail && student.detail.length > 0) {
     history.push('/student/classes')
    } else {
      history.push('/student/profile')
    }
  } else {
    history.push('/faculty/classes')
  }
}

}, [auth.authenticate]);

谁能帮帮我

【问题讨论】:

  • 你可以有两个 useEffect,on 会在 mount 时调用,发送学生详细信息,另一个可能是你在描述中的那个,它将检查身份验证依赖关系和触发历史记录。跨度>

标签: reactjs redux async-await react-redux react-hooks


【解决方案1】:

由于 API 调用是异步的,您可以添加一个 awaitthen 来等待响应,然后执行接下来的操作

useEffect(() => {
  async function authenticateUser(){
  const id = auth.user.user;
  await dispatch(getStudent(id));

  if (auth.authenticate) {
    if (auth.user.user_type.is_student == true) {
      if (student.detail && student.detail.length > 0) {
       history.push('/student/classes')
      } else {
        history.push('/student/profile')
      }
    } else {
      history.push('/faculty/classes')
   }
  }
 }
 authenticateUser()
}, [auth.authenticate]);

或者使用 then as

const auth = useSelector((state) => state.auth);
const student = useSelector((state) => state.student);
useEffect(() => {
const id = auth.user.user;
dispatch(getStudent(id)).then(() => {
      if (auth.authenticate) {
       if (auth.user.user_type.is_student == true) {
         if (student.detail && student.detail.length > 0) {
          history.push('/student/classes')
         } else {
           history.push('/student/profile')
          }
      } else {
    history.push('/faculty/classes')
  }
}    })
}, [auth.authenticate]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多