簡體   English   中英

從請求分派Redux動作的正確方法

[英]Correct way to dispatch redux action from request

我正在使用redux-thunk,並且有以下操作:

export const fetchUserInfo = () => dispatch => {
  return fetchCurrentUser()
    .then(user => {
      dispatch(retrieveUser(user));

      if (user && user.settings && user.settings.storePageId) {
        dispatch(getStoreById(user.settings.storePageId));
      }

      return user;
    })
    .catch(err => {
      console.error('Fetching userinfo failed', err);
      return Promise.reject(err);
    });
};

fetchCurrentUser是一個api調用,定義如下:

export const fetchCurrentUser = () => authenticatedRequest('/customer');

這是我的authenticatedRequest:

import { logoutUser } from '../../actions/auth';
export const authenticatedRequest = (url, opts = {}, req = request) => {
  if (!cachedTokenType || !cachedAccessToken) {
    logoutUser() // I want this to happen!! :(

    return Promise.reject(
      new Error(
        'Missing token_type & access_token needed to perform this request'
      )
    );
  }

  const headers = { ...defaultOpts.headers, ...(opts.headers || {}) };

  const authedOpts = {
    ...opts,
    headers: {
      ...headers,
      Authorization: `${cachedTokenType} ${cachedAccessToken}`
    }
  };

  return req(url, authedOpts);
};

我希望能夠在我的authenticatedRequest函數中調度logoutUser(),因此我不必在所有使用authenticatedRequest的地方重復此邏輯。 我的問題是我不知道如何從另一個文件調用redux動作,以及何時不在帶有connect的react組件中。

I want to be able to dispatch logoutUser() in my authenticatedRequest func...

我要說的是,通過實現這一點, authenticatedRequest不僅可以完成一件事(對用戶進行身份驗證並可能注銷用戶)。 隨着時間的流逝,如果您想將redux-thunk更改為其他內容,復雜性可能會增加並且變得更糟。

如果仍然需要它,則可以傳播dispatch以便可以調度其他操作:

const fetchCurrentUser = (dispatch) => authenticatedRequest(dispatch, '/customer')

const authenticatedRequest = (dispatch, url, opts = {}, req = request) => {
  if (YOUR_CONDITION) {
    dispatch(logoutUser())
  }
  ...
}

我個人不會這樣做,因為它會將dispatch公開給外部呼叫。 這是您的選擇:)

是否可以在fetchUserInfo操作中處理logoutUser

const authenticatedRequest = (url, opts = {}, req = request) => {
  if (YOUR_CONDITION) {
    return Promise.reject('LOGOUT')
  }
  ...
}

const fetchUserInfo = () => dispatch => {
  return fetchCurrentUser()
    .then(user => {
      ...
    })
    .catch(err => {
      if (err === 'LOGOUT') {
        dispatch(logoutUser())
      }
    })
}

暫無
暫無

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

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