正确调度注销操作 redux-saga

Correctly dispatching logout action redux-saga

我有一个使用以下代码处理 HTTP 请求的应用程序:

import { logout } from '../containers/App/actions';
import store from '../store';

/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options) {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': 'Content-Type, Authorization'
  };
  const token = localStorage.getItem('token');
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  const newOptions = {
    ...options,
    mode: 'cors',
    headers
  };
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
    .catch(err => {
      // check for 401 here and throw an action to clean the store and logout.
      console.log(err);
      if (err.response.status === 401) {
        store.dispatch(logout);
      }
      throw err;
    });
}

除其他事项外,处理程序检查错误代码并分派注销操作以清理存储和会话。我的注销操作定义为:

export function logout() {
  return {
    type: LOGOUT
  };
}

但是,代码无法正常工作。我的 dispatch(logout) 导致以下错误:Error: Actions must be plain objects. Use custom middleware for async actions.

我该如何解决这个问题?

您正在传递调度函数 logout,因此它会显示此错误。您需要这样编辑:

store.dispatch(logout();

更新:如果你想logout是一个异步函数,你可以更新这个函数:

function logout() {
  return async (dispatch) => {
    await logout();

    dispatch({
      type: LOGOUT,
    });
  };
}
 store.dispatch(logout());