简体   繁体   English

从请求分派Redux动作的正确方法

[英]Correct way to dispatch redux action from request

I am using redux-thunk and I have the following action: 我正在使用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 is an api call defined as such: fetchCurrentUser是一个api调用,定义如下:

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

Here is my authenticatedRequest: 这是我的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);
};

I want to be able to dispatch logoutUser() in my authenticatedRequest func so I dont have to duplicate this logic at all the places using authenticatedRequest. 我希望能够在我的authenticatedRequest函数中调度logoutUser(),因此我不必在所有使用authenticatedRequest的地方重复此逻辑。 My problem is I dont know how to call a redux action from another file and when not in a react component with connect. 我的问题是我不知道如何从另一个文件调用redux动作,以及何时不在带有connect的react组件中。

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

I'd say that by achieving that, authenticatedRequest is doing more than one thing (authenticating and possibly logging users out). 我要说的是,通过实现这一点, authenticatedRequest不仅可以完成一件事(对用户进行身份验证并可能注销用户)。 With time, complexity might increase and gets worst in case you want to change redux-thunk to something else. 随着时间的流逝,如果您想将redux-thunk更改为其他内容,复杂性可能会增加并且变得更糟。

Should you still need it, you can propagate dispatch so you can dispatch other actions: 如果仍然需要它,则可以传播dispatch以便可以调度其他操作:

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

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

I personally wouldn't do that since it exposes dispatch to external calls. 我个人不会这样做,因为它会将dispatch公开给外部呼叫。 It's your choice though :) 这是您的选择:)

Is it possible to handle logoutUser in fetchUserInfo action? 是否可以在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