javascript - TypeError (0 , _index.DEC_NUM) 不是函数
问题描述
所以我收到 DEC_NUM 不是函数的错误。我正在使用 react-redux 创建一个计数器状态。当我点击计数器(+)时,我收到了这个错误。
这是我的代码:Action/index.js
const INC_NUM = () => {
return {
type: "INC_NUMBER"
};
};
const DEC_NUM = () => {
return {
type: "DEC_NUMBER"
};
};
export default { INC_NUM, DEC_NUM };
减速器/counterReducer.js
const counterReducer = (state = 1, action) => {
if (action.type === "INC_NUMBER") {
console.log("Pressed +");
} else if (action.type === "DEC_NUMBER") {
console.log("Pressed -");
}
return state;
};
export default counterReducer;
减速器/index.js
import counter from "./counterReducer";
import { combineReducers } from "redux";
const rootReducer = combineReducers({
counter
});
export default rootReducer;
Store.js
import rootReducer from "./Reducer/index";
import { createStore } from "redux";
const store = createStore(rootReducer);
export default store;
主要代码 App.js
import "./styles.css";
import { INC_NUM, DEC_NUM } from "./Action/index";
import { useSelector, useDispatch } from "react-redux";
export default function App() {
const count = useSelector((state) => state.counter);
const dispatch = useDispatch();
return (
<div className="App">
<h1>Reducer Counter</h1>
<button
onClick={() => {
dispatch(DEC_NUM());
}}
>
-
</button>
<span>{count}</span>
<button
// onClick={() => {
// dispatch(INC_NUM());
// }}
>
+
</button>
</div>
);
}
主要错误来自上面的代码,只是 DEC_NUM 不是函数
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import store from "./store";
import { Provider } from "react-redux";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
rootElement
);
解决方案
您只需像这样导出(不是默认|正常)它->
export const INC_NUM = () => {
return {
type: "INC_NUMBER"
};
};
export const DEC_NUM = () => {
return {
type: "DEC_NUMBER"
};
};
-------------
import { INC_NUM, DEC_NUM } from "./Action/index";
注意:您不能像这样解构默认导出。对于您的情况,如果您愿意,可以使用:
const INC_NUM = () => {
return {
type: "INC_NUMBER"
};
};
const DEC_NUM = () => {
return {
type: "DEC_NUMBER"
};
};
export default { INC_NUM, DEC_NUM };
-----------------------
import counterActions from "./Action/index";
const onClick => dispatch(counterActions.INC_NUM())
推荐阅读
- python - 在 Django 中实现“已保存的书籍”购物车
- snowflake-cloud-data-platform - 是否可以取消设置 Snowflake 任务的 WHEN 条件?
- javascript - IE9:如果字符串的值在对象数组中匹配,则操作字符串
- powershell - Powershell 只输出第一个字符
- html - 使用 Font Awesome Kit 时,CORS 策略已阻止访问脚本
- python - 从 scikit-learn 中的 LinearSVC 中获取最具选择性的特征以进行多类预测
- jquery - 用于关闭和打开对话框 jquery 的相同按钮
- scala - Spark Scala Jupyter 笔记本全宽
- android - 在 ViewPager 抽屉布局中加载成像器的空指针 - 如何解决这个问题?
- javascript - 即使在缓存策略中提及关键字段后,useQuery 也不会缓存数据