【问题标题】:Correctly dispatching logout action redux-saga正确调度注销动作 redux-saga
【发布时间】:2021-04-20 00:42:43
【问题描述】:

我有一个带有以下代码的应用程序来处理 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;
    });
}

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

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

但是,代码没有按我的意愿工作。我的dispatch(logout) 导致以下错误:Error: Actions must be plain objects. Use custom middleware for async actions.

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs redux redux-saga redux-store


    【解决方案1】:

    你正在传递一个函数logout,所以它会显示这个错误。你需要这样编辑:

    store.dispatch(logout();
    

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

    function logout() {
      return async (dispatch) => {
        await logout();
    
        dispatch({
          type: LOGOUT,
        });
      };
    }
     store.dispatch(logout());
    

    【讨论】:

    • 该动作并不是真正的异步,但你对我没有正确调用该动作是正确的。 store.dispatch(logout()); 而不是 store.dispatch(logout);解决了这个问题。谢谢。
    最近更新 更多