reactjs - 为什么我的 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
)
错误在哪里?感谢回复!!!
解决方案
你快到了。有几件事要改变:
调度动作
从调用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,
};
推荐阅读
- javascript - 仅在特定条件为真时调用特定函数
- python - 将 utf-8 字节转换为字符串 python
- c# - UWP 证书去哪了?
- python - 如何始终在 Python Cmd2 应用程序中启用调试?
- javascript - 带 TypeScript 的 Stripe ElementsConsumer:传递道具?
- python-3.x - Python 3:执行包含带有索引和触发器的 DDL 的 oracle SQL 脚本
- javascript - 我如何有一个按钮来触发一个新的文本框被创建?(反应)
- makefile - Makefile 分割变量
- java - 用于扫描仪验证的多个条件 while 循环
- spring-boot - 使用 Spring Boot 发送多部分请求,每个部分都有特定的标头