首页 > 解决方案 > 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
);

标签: javascriptreactjsreact-reduxfrontend

解决方案


您只需像这样导出(不是默认|正常)它->

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())


推荐阅读