首页 > 解决方案 > 为什么我的 redux 状态总是以默认情况返回?

问题描述

我正在使用 react-redux 但我看不到我的状态。当我检查我的状态时,它总是返回我的默认值。我检查我的类型,但它返回真值。哪里有问题 ?感谢帮助

我的行动:

import { 
  SET_MENULIST
} from "../constants/Menu";

export const makeMenu = (menuList) => {
  return {
    type: SET_MENULIST,
    menuList,
  };
};

我的减速机:

const menu = (state = {}, action) => { 

  switch (action.type) {
    case SET_MENULIST:
      return {
        menuList: action.menuList,
      };
 
    default:
      return "err";
  }
};
export default menu;

我的 reducer/index.js (combineReducers) :

import { combineReducers } from "redux";
import Auth from "./Auth";
import Theme from "./Theme";
import Menu from "./Menu";
const reducers = combineReducers({
  theme: Theme,
  auth: Auth,
  menu: Menu,
});

export default reducers;

我尝试像makeMenu(data); 在我的页面上一样使用它并像这样测试它:

const test = useSelector((state) => state.menu);
 console.log(test) //Its returns "err" (Default value of my reducer

)

错误在哪里?感谢回复!!!

标签: reactjsreduxreact-redux

解决方案


你快到了。有几件事要改变:

调度动作

从调用makeMenu函数的位置,您必须调度操作。例子:

import {useDispatch} from 'react-redux'
import {makeMenu} from './path/to/makeMenu'

const ComponentExample = props => {
  const dispatch = useDispatch()
  
  dispatch(makeMenu(menuList)) /* call this wherever you want to call makeMenu */

}

奖励:从减速器返回

当您像这样从 reducer 返回一个新对象时,您将覆盖其他值,因此可能会出现错误。

case SET_MENULIST:
      return {
        menuList: action.menuList,
      };

您可能想要使用扩展运算符:

case SET_MENULIST:
      return {
        ...state,
        menuList: action.menuList,
      };

推荐阅读