我正在学习redux,并在YouTube视频后尝试了一些代码。我创建了一个简单的Vanilla JS应用程序并在其中安装了redux,但当我在终端中运行应用程序时,我得到了“错误:根reducer应为函数。但收到的却是:'未定义'“
下面是我的index.js文件
const redux = require("redux");
const legacy_createStore = redux.legacy_createStore();
const BUY_CAKE = "BUY_CAKE"; //define action type
//Action creator function that returns the action object
function buyCake() {
//action object with type as type of action and some other info
return {
type: BUY_CAKE, //set action type
info: "first redux action",
};
}
//(prevState, action) => newState
const initialState = {
numberOfCakes: 10,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case BUY_CAKE:
return {
//always return new state objet since a reducer is a pure function
...state, //state object might have other states as well so it is safer to copy those states first and change the required state
numberOfCakes: state.numberOfCakes - 1,
};
default:
return state;
}
};
const store = legacy_createStore(reducer);
console.log("Initial state : ", store.getState());
const unsubscribe = store.subscribe(() =>
console.log("Update state : ", store.getState())
);
store.dispatch(buyCake());
store.dispatch(buyCake());
store.dispatch(buyCake());
store.dispatch(buyCake());
unsubscribe();
错误堆栈如下:
Error: Expected the root reducer to be a function. Instead, received: 'undefined'
at Object.createStore (D:\Taha\YouTube\Redux\redux_demo\node_modules\redux\lib\redux.js:166:11)
at Object.<anonymous> (D:\Taha\YouTube\Redux\redux_demo\index.js:2:34)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
下面是我的Package.json
{
"name": "redux_demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"redux": "^4.2.1"
}
}
1条答案
按热度按时间eeq64g8w1#
删除此行:
const legacy_createStore = redux.legacy_createStore();
像这样使用: