【问题标题】:Redux store reducers implement wrong interfacesRedux store reducer 实现了错误的接口
【发布时间】:2021-04-17 07:21:28
【问题描述】:

我用 2 个不同的“切片”创建了一个 redux 商店。首先,我有一个 appSlice:

appSlice.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";

export interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

export const appSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = appSlice.actions;

export const selectCount = (state: RootState) => state.app.value;

export default appSlice.reducer;

我有一个 cameraSlice.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";

export interface CameraState {
    cameraImage: string | null;
}

const initialState: CameraState = {
  cameraImage: null,
};

export const cameraSlice = createSlice({
  name: "camera",
  initialState,
  reducers: {
    setCameraImage: (state, action: PayloadAction<string>) => {
      state.cameraImage = action.payload;
    },
    resetCameraImage: (state) =>{
        state.cameraImage=null;
    }
  },
});

export const { setCameraImage, resetCameraImage } = cameraSlice.actions;

export const selectCameraImage = (state: RootState) => state.camera.cameraImage;

export default cameraSlice.reducer;

来自这个selectCameraImage的错误,错误信息:Property 'cameraImage' does not exist on type 'CounterState'.

现在我的商店是这样的: store.ts

import { configureStore } from "@reduxjs/toolkit";
import appReducer from "./appSlice";
import cameraReducer from "./appSlice";

export const store = configureStore({
  reducer: {
    app: appReducer,
    camera: cameraReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

hooks.ts:

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

我该如何解决这个问题?现在,应用程序和相机都是 CounterState 类型,我不知道为什么。 如果您有任何想法,请告诉我!感谢您的宝贵时间!

【问题讨论】:

    标签: javascript reactjs typescript redux react-redux


    【解决方案1】:

    我没有在任何地方看到CounterState 的定义,所以也许你只是有另一个文件飞来飞去? 另外,如果你看看你的进口,

    import appReducer from "./appSlice";
    import cameraReducer from "./appSlice";
    

    肯定是错的。

    【讨论】:

    • 天哪,愚蠢的错误,非常感谢!:D
    猜你喜欢
    • 2018-09-18
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2016-09-08
    • 1970-01-01
    相关资源
    最近更新 更多