如何在重定向完成后调度动作(Redux)?

时间:2018-01-11 11:14:14

标签: javascript facebook reactjs redux

只要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');
      }
    });
  }

我的问题是如何在页面重定向完成后调度操作。 因为使用上面的代码,微调器会在请求解决后立即停止,并且不关心重定向过程。

1 个答案:

答案 0 :(得分:1)

根据我的回答,我假设您可以控制重定向后呈现的组件。如果是这种情况,您可以简单地将dispatch(itemsIsLoading(false))放在重定向后立即呈现的组件的componentDidMount挂钩内。在requestLogin内你可以做这样的事情:

  .
  .
  .
  callback();

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

希望这能解决你的问题!