TypeError:无法解构'(0,react_redux__WEBPACK_IMPORTED_MODULE_3__.useSelector)(...)'的属性'count',因为它是未定义的

IT技术 reactjs redux next.js
2022-07-24 23:39:53

按照本教程:https ://www.youtube.com/watch?v=iBUJVy8phqw

我想在我的 Next.js 应用程序中设置 REdux。但我被卡住了。不知道为什么。一切都与教程中的相同。

计数器.js:

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

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0,
  },
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    },
    incrementByAmount: (state, action) => {
      state.count += action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

商店.tsx:

import { configureStore } from "@reduxjs/toolkit";
import { counterReducer } from "./counter";

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
});

onboarding2.tsx 的第一部分:

import Head from "next/head";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";

export const fallBackLang = "hu";

interface Onboarding2Props {
  lang: string;
  translations: Translation;
}

export default function Onboarding2(props: Onboarding2Props) {
  const { lang, translations } = props;
  const { count } = useSelector((state) => state.counter);

在此处输入图像描述

2个回答

您尝试导入 counter.js 中不存在的“counterReducer”

'counterReducer' 应该是从 counter.js 中默认导出的 counterSlice.reducer

你可以简单地替换

import { counterReducer } from "./counter";

import counterReducer from "./counter";

在您的 store.js 文件中

我有一个类似的问题,解决方案是将减速器添加到商店:

...减速器:{count:countReducer} ...