Redux从另一个thunk调度thunk,从最后一个thunk调度不会发生

时间:2019-01-17 09:27:48

标签: reactjs redux redux-thunk

因此,在重构此代码之后

export const login: ({ userName: string, password: string }) => TThunkAction =
  ({ userName, password }) => async (dispatch, getState) => {
    const SIGN_IN_URL = '/signin';
    const res: $AxiosXHR<{username: string, password: string}, TLoginResData> =
      await api1.post(SIGN_IN_URL, { username: userName, password })
        .catch((err) => {
          throw new SubmissionError({ _error: err.response.data.message });
        });
    const data: TLoginResData = res.data;
    if (data && data.token && data.result) {
      const state = { token: data.token, profile: data.result };
      dispatch(onLogin(state));
      setAuthToken(data.token, api1);
      const res: $AxiosXHR<void, TPermissionResData> =
        await api1.get('/permissions')
          .catch(throwBadResult);
      const permissions: TPermissions =
        [...res.data.result, ...localPermissions];
      dispatch(onPermissionsGet(permissions));
      dispatch(push('/dashboard'));
      localStorage.setItem('auth', state.token);
    } else {
      throwBadResult();
    }
  };

对此

const getPermissions: () => TThunkAction =
  () => async (getState, dispatch) => {
    console.log('getPermissions');
    const res: $AxiosXHR<void, TPermissionResData> =
      await api1.get('/permissions')
        .catch(throwBadResult);
    const permissions: TPermissions =
      [...res.data.result, ...localPermissions];
    dispatch(onPermissionsGet(permissions));
  };

export const login: ({ userName: string, password: string }) => TThunkAction =
  ({ userName, password }) => async (dispatch, getState) => {
    const SIGN_IN_URL = '/signin';
    const res: $AxiosXHR<{username: string, password: string}, TLoginResData> =
      await api1.post(SIGN_IN_URL, { username: userName, password })
        .catch((err) => {
          throw new SubmissionError({ _error: err.response.data.message });
        });
    const data: TLoginResData = res.data;
    if (data && data.token && data.result) {
      const state = { token: data.token, profile: data.result };
      dispatch(onLogin(state));
      setAuthToken(data.token, api1);
      await dispatch(getPermissions());
      dispatch(push('/dashboard'));
      localStorage.setItem('auth', state.token);
    } else {
      throwBadResult();
    }
  };

发生一件奇怪的事情。

getPermissions被呼叫。

它成功获得响应。

发送onPermissionsGet

export const onPermissionsGet = (payload: TPermissions) => ({
  type: ON_PERMISSIONS_GET,
  payload,
});

然后...什么都没发生。

在devtools中,我看不到ON_PERMISSIONS_GET

但是,如果我将console.log放在onPermissionsGet中,似乎可以正常调用了。

没有这种重构就没有问题。

0 个答案:

没有答案