使用 redux-toolkit 时 reducer 函数错误

reducer function error when using redux-toolkit

我在使用 redux 时出现了以下错误:

TypeError: react__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function

我该如何解决这个问题?我添加了下面的代码。

dispatch() 正在以下组件中调用

import authAction from "../store/Auth";
import { useDispatch } from "react-redux";
const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
}));

export default function Header() {
  const classes = useStyles();
  const dispatch = useDispatch();
  console.log("Auth:", authAction);

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <Typography variant="h6" className={classes.title}>
            Counter
          </Typography>
          <Button
            color="inherit"
            onClick={() => {
              dispatch(authAction.login());
            }}
          >
            Login
          </Button>
        </Toolbar>
      </AppBar>
    </div>
  );
}

creatSlice 分量:

import { createSlice } from "@reduxjs/toolkit";

const authSlice = createSlice({
  name: "Auth",
  initialState: { loggedIn: false },
  reducers: {
    login(state) {
      state.loggedIn = true;
    },
  },
});

export const authActions = authSlice.actions;

export default authSlice.reducer;

configureStore 分量:

import { configureStore } from "@reduxjs/toolkit";
import auth from "./Auth";

const store = configureStore({
  reducer: {
    auth: auth,
  },
});

export default store;

谢谢。

问题

您的身份验证操作不是您切片的默认导出:

export const authActions = authSlice.actions;

export default authSlice.reducer;

但您正在导入它们,就好像它们是:

import authAction from "../store/Auth";

解决方案

正确导入命名的 authActions 导出:

import { authActions } from "../store/Auth";

并派遣正确的动作创建者:

<Button
  color="inherit"
  onClick={() => {
    dispatch(authActions.login());
  }}
>
  Login
</Button>