【问题标题】:When I combine reducers for some reason my auth reducer is not attaching itself to the store, how is that?当我出于某种原因组合减速器时,我的 auth 减速器没有附加到商店,那是怎么回事?
【发布时间】:2020-07-31 01:55:45
【问题描述】:

See image explanation of problem

问题:

当导入并尝试与其他 reducer 结合时,auth reducer 未在全局商店中得到识别。其中alertprofile&post等其他reducer已经被全球商店认可。

 

Auth Reducer:

Github:https://github.com/DariusRain/Pluto/blob/master/client/src/redux/modules/auth.js

import api from "../../utils/api";
import { setAlert } from "./alert";

// Action Types
export const REGISTER_SUCCESS = "PLUTO/AUTH/REGISTER_SUCCESS";
export const REGISTER_FAIL = "PLUTO/AUTH/REGISTER_FAIL";
export const LOGIN_SUCCESS = "PLUTO/AUTH/LOGIN_SUCCESS";
export const LOGIN_FAIL = "PLUTO/AUTH/LOGIN_FAIL";
export const USER_LOADED = "PLUTO/AUTH/USER_LOADED";
export const AUTH_ERROR = "PLUTO/AUTH/ERROR";
export const LOGOUT = "PLUTO/AUTH/LOGOUT";
export const ACCOUNT_DELETED = "PLUTO/AUTH/ACCOUNT_DELETED";

// Reducer
const initialState = {
  token: localStorage.getItem("token"),
  isAuthenticated: null,
  loading: true,
  user: null,
};

export default (state = initialState, { type, payload }) => {
  switch (type) {
    case USER_LOADED:
      return {
        ...state,
        isAuthenticated: true,
        loading: false,
        user: payload,
      };
    case REGISTER_SUCCESS:
      return {
        ...state,
        ...payload,
        isAuthenticated: true,
        loading: false,
      };
    case LOGIN_SUCCESS:
      return {
        ...state,
        ...payload,
        isAuthenticated: true,
        loading: false,
      };
    case ACCOUNT_DELETED:
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        loading: false,
        user: null,
      };
    case REGISTER_FAIL:
    case AUTH_ERROR:
    case LOGOUT:
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        loading: false,
        user: null,
      };
    default:
      return state;
  }
};


// Action Creators
export const loadUser = () => async (dispatch) => {
  try {
    const res = await api.get("/auth");
    dispatch({
      type: USER_LOADED,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};
// Register User
export const register = (formData) => async (dispatch) => {
  try {
    const res = await api.post("/users", formData);
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
    dispatch(loadUser());
  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
    }
    dispatch({
      type: REGISTER_FAIL,
    });
  }
};

// Login User
export const login = (email, password) => async (dispatch) => {
  try {
    const res = await api.post("/auth", { email, password });
    dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data,
    });
    dispatch(loadUser());
  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
    }
    dispatch({
      type: LOGIN_FAIL,
    });
  }
};
// Logout
export const logout = () => async (dispatch) => dispatch({ type: LOGOUT });

 

组合减速器

Github:https://github.com/DariusRain/Pluto/blob/master/client/src/redux/modules/index.js

import {
  combineReducers
} from "redux";
import alert from "./alert";
import post from "./post";
import profile from "./profile";
import auth from "./auth";

export default combineReducers({
  alert,
  profile,
  post,
  auth,
});

 

商店

Github:https://github.com/DariusRain/Pluto/blob/master/client/src/redux/index.js

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './modules';
import setAuthToken from '../utils/setAuthToken';

const initialState = {};

const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

let currentState = store.getState();

store.subscribe(() => {
  let previousState = currentState;
  currentState = store.getState();
  if (previousState.auth.token !== currentState.auth.token) {
    const token = currentState.auth.token;
    setAuthToken(token);
  }
});

export default store;

存储库:

冥王星:https://github.com/DariusRain/Pluto

 

感谢您的帮助! ??? -DariusRain

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    您遇到了循环依赖问题。当您初始化商店时,您将其导入:

    1. App.js -> 从 './redux' 导入存储;

    2. 存储初始化:

      a) redux/modules/auth.js -> 从 "../../utils/api" 导入 api

      b) utils/api.js -> import store from '../redux' -> 你会崩溃

    我建议将 reducer 和 action creators 拆分到单独的文件中

    【讨论】:

    • 谢谢@Sergey,应用程序现在似乎正在运行,决定只导入和使用“axios”而不是导入和使用“api”。
    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    相关资源
    最近更新 更多