简体   繁体   English

React + Redux:如何等待一个动作完成然后重定向

[英]React + Redux: How to wait for an action to complete and then redirect

I am new to React but I've been working on Vue for many years.我是 React 的新手,但我已经在 Vue 上工作了很多年。 I am now stuck in one area when I need to wait for an action to complete.当我需要等待操作完成时,我现在被困在一个区域。 After the action is complete I have to make another action call or do some operations there.动作完成后,我必须进行另一个动作调用或在那里进行一些操作。 But it is not waiting for the action to complete and start executing the code below that.但它不是等待动作完成并开始执行下面的代码。

Method:方法:

export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({
      type: USER_LOGIN_REQUEST,
    })

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const { data } = await axios.post(
      '/users/login',
      { email, password },
      config
    )

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    })

    localStorage.setItem('userInfo', JSON.stringify(data))
  } catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    })
  }
}

Method from where action is dispatched:派发动作的方法:

const redirect = location.search ? location.search.split('=')[1] : '/'

const submitHandler = (e) => {
  e.preventDefault()
  dispatch(login(email, password))
  history.push(redirect)
}

Now, in the above code, the redirection is not waiting for the dispatch to complete.现在,在上面的代码中,重定向不等待调度完成。 I tried this one but it is not working:我试过这个,但它不工作:

const submitHandler = async (e) => {
  e.preventDefault()
  await dispatch(login(email, password))
  history.push(redirect)
}

Let's assume that when the below让我们假设当下面

dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    })

happens that your reduxState has some sort of property like isLoggedIn or isAuthenticated .碰巧您的reduxState具有某种属性,例如isLoggedInisAuthenticated Now you can use the same property to trigger a redirect inside a useEffect like so:-现在您可以使用相同的属性在useEffect中触发redirect ,如下所示:-

const {isAuthenticated} = reduxState;
useEffect(()=>{
if(isAuthenticated) history.push(redirect);
},[isAuthenticated])

and your submitHandler can be the following:-并且您的submitHandler可以是以下内容:-

const submitHandler = (e) => {
  e.preventDefault()
  dispatch(login(email, password))
}

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

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