簡體   English   中英

重定向完成后如何調度動作(Redux)?

[英]How to dispatch an action(Redux) after redirection is done?

我正在嘗試使“加載”微調器一直顯示,直到Facebook身份驗證正在進行。 完成請求+頁面重定向后,隱藏加載微調器。

在這種情況下,可以通過單擊登錄按鈕來完成對Facebook的身份驗證,然后瀏覽器將重定向到http:// localhost:3000 / auth / facebook

到目前為止,這是我嘗試過的。

我制作了一個reducer來存儲加載狀態,以后可以使用操作來覆蓋它。

dispatch(itemsIsLoading(true));

Redux狀態樹:

{
  ...
  isLoading: loadingReducer
}

這是操作的代碼。

export const requestLogin = ({ username, password }, callback) => async dispatch => {
  // Show the loading spinner
    dispatch(itemsIsLoading(true));

  const res = await axios.post('/api/authenticate', {
    username,
    password
  });

  dispatch({ type: REQUEST_LOGIN, payload: res.data });

  // Redirect to/auth/facebook after login amember is success
  callback();

  // Stop spinner and show the content
  dispatch(itemsIsLoading(false));
};

 export function itemsIsLoading(bool) {
  return {
    type: ITEMS_IS_LOADING,
    isLoading: bool
  };
}

這是提交登錄表單后我使用的方法

 onFormSubmit = async (e) => {
    e.preventDefault();

    let dataLogin = {
      username: this.username.value.trim(),
      password: this.password.value.trim(),
    }

    this.props.requestLogin(dataLogin, () => {
      switch (this.props.auth) {
        case 1:
          this.props.redirect(true, '/auth/facebook');
          break;
        case 2:
          toast.warn('Your license is expired. Contact iqbal bro');
          break;
        case 3:
          toast.error('Username or password is not match');
          break;
        default:
          console.log('Something is wrong, please contact administrator');
      }
    });
  }

我的問題是頁面重定向完成后如何調度動作。 因為使用上面的代碼,微調器將在請求被解決后立即停止,並且與重定向過程無關。

根據我的回答,我假設您可以控制重定向后呈現的組件。 如果是這種情況,您只需將dispatch(itemsIsLoading(false))放在重定向后立即呈現的組件的componentDidMount掛鈎中。 requestLogin內部,您可以執行以下操作:

  .
  .
  .
  callback();

  if(!res.data.successfulAuth) {
    dispatch(itemsIsLoading(false));
  }
};


希望這能解決您的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM