开发者问题收集

React Redux Toolkit:TypeError:无法读取未定义的属性“value”

2021-06-03
4760

在我的项目中,我已经为 2 种不同的状态场景实现了 React Redux 工具包,它们运行完美。现在我需要为 Redux 实现第三个状态场景,因此我遵循了与前两个相同的模式。灵感来自: https://react-redux.js.org/tutorials/quick-start

我的第三个状态场景具有以下切片声明:

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

export const betsSlice = createSlice({
  name: "bets",
  initialState: { value: { betsLeft: 0, betToBet: 0, usersBets: "" } },
  reducers: {
    updateBets: (state, action) => {
      state.value = action.payload;
    },
  },
});

export const { updateBets } = betsSlice.actions;

/**
 * Exporting to avoid boilerplate like:
 * const count = useSelector((state) => state.counter.value)
 */
export const getBets = (state) => state.bets.value;

export default betsSlice.reducer;

store.js:

import { configureStore } from "@reduxjs/toolkit";
import themeModeReducer from "../features/themeMode/themeModeSlice";
import liveGeneralStatisticsReducer from "../features/liveGeneralStatistics/liveGeneralStatisticsSlice";
import betsReducer from "../features/bets/betsSlice";

export default configureStore({
  reducer: {
    themeMode: themeModeReducer,
    liveGeneralStatistics: liveGeneralStatisticsReducer,
    betsReducer: betsReducer,
  },
});

并且在我通常在开始时调用的组件中:

const betsRedux = useSelector(getBets);

但是,出乎意料的是,在渲染时,我得到: TypeError:无法读取未定义的属性“值”

指向在:

  16 |  * Exporting to avoid boilerplate like:
  17 |  * const count = useSelector((state) => state.counter.value)
  18 |  */
> 19 | export const getBets = (state) => state.bets.value;
  20 | 
  21 | export default betsSlice.reducer;
  22 | 

我不明白为什么会发生这种情况,因为我们已经设置了 initialState。

请问有什么方法可以解决这个问题?

1个回答

configureStore 在后台使用 combineReducers(reducers)

You can control state key names by using different keys for the reducers in the passed object. For example, you may call combineReducers({ todos: myTodosReducer, counter: myCounterReducer }) for the state shape to be { todos, counter } .

对于您而言,应将 betsReducer 键替换为 bets ,如下所示:

export default configureStore({
  reducer: {
    themeMode: themeModeReducer,
    liveGeneralStatistics: liveGeneralStatisticsReducer,
    bets: betsReducer,
  },
});

状态形状将为: { themeMode, liveGeneralStatistics, bets }

然后, export const getBets = (state) => state.bets.value; 选择器将起作用。

Lin Du
2021-06-07