You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux嵌套对象状态更新报错:game.state未定义问题求助

问题

开发一款用Redux统计答题对错的游戏时,触发状态更新出现错误:Uncaught TypeError: game.state is undefined,所有导入无语法错误,相关代码如下:

状态切片代码

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

const initialState = {
  flags: { correct: 0, incorrect: 0 },
  languages: { correct: 0, incorrect: 0 },
  regions: { correct: 0, incorrect: 0 },
  currency: { correct: 0, incorrect: 0 },
  capitals: { correct: 0, incorrect: 0 },
  start: false,
};

const gameSlice = createSlice({
  name: "game",
  initialState,
  reducers: {
    addError(state, action: PayloadAction<string>) {
      switch (action.payload) {
        case "flags":
          state.flags.incorrect++;
          break;
        case "languages":
          state.languages.incorrect++;
          break;
        case "regions":
          state.regions.incorrect++;
          break;
        case "currency":
          state.currency.incorrect++;
          break;
        case "capitals":
          state.capitals.incorrect++;
          break;
      }
    },
    addCorrect(state, action: PayloadAction<string>) {
      switch (action.payload) {
        case "flags":
          state.flags.correct++;
          break;
        case "languages":
          state.languages.correct++;
          break;
        case "regions":
          state.regions.correct++;
          break;
        case "currency":
          state.currency.correct++;
          break;
        case "capitals":
          state.capitals.correct++;
          break;
      }
    },
  },
});

export const { addError, addCorrect } = gameSlice.actions;
export default gameSlice.reducer;

main.tsx代码

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { ApiProvider } from "@reduxjs/toolkit/query/react";
import { BrowserRouter } from "react-router-dom";
import { apiSlice } from "./features/api/apiSlice";
import { Provider } from "react-redux";
import { store } from "./features/app/store";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <Provider store={store}>
      <ApiProvider api={apiSlice}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </ApiProvider>
    </Provider>
  </React.StrictMode>
);

触发状态更新的函数

function handleClick(
  e: React.MouseEvent<HTMLButtonElement>,
  country: string
) {
  e.preventDefault();
  if (country === region) {
    alert("correct!");
    dispatch(addCorrect("regions"));
    setRandom(Math.floor(Math.random() * 249) + 1);
  } else {
    dispatch(addError("regions"));
  }
}

错误原因及解决方法

核心原因

gameSlice的reducer未在Redux store中注册,导致store里不存在game状态节点,组件访问相关状态时就会抛出undefined错误。

解决步骤

  1. 修改store配置文件(路径为./features/app/store.ts),导入并注册game reducer:
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from '../api/apiSlice';
import gameReducer from '../path-to-game-slice/gameSlice'; // 替换为你的gameSlice实际路径

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    game: gameReducer, // 关键:添加该行注册game reducer
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
});
  1. 修正组件中状态的访问路径
    用useSelector获取状态时,直接访问store中的game节点,而非game.state:
import { useSelector } from 'react-redux';

// 正确写法
const regionsStats = useSelector((state) => state.game.regions);
  1. 确认dispatch的正确使用
    组件中需正确导入useDispatch并初始化:
import { useDispatch } from 'react-redux';
import { addCorrect, addError } from '../path-to-game-slice/gameSlice';

const dispatch = useDispatch();

内容的提问来源于stack exchange,提问作者ether

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:21:36