大家好,我有个问题,
这是 codeSilce.ts 文件
import { createSlice } from "@reduxjs/toolkit";
const codeSlice = createSlice({
name: "codeApply",
initialState: {
codeOTP: "",
token: "",
},
reducers: {
addcode: (state, action) => {
state.codeOTP = action.payload;
},
setToken: (state, action) => {
state.token = action.payload;
},
},
});
export const { addcode, setToken } = codeSlice.actions;
export default codeSlice.reducer;
这是reducer文件
import codeSlice from 'app/slices/codeSlice';
const rootReducer = {
code: codeSlice
};
export type reducer = typeof rootReducer;
export default rootReducer;
这是商店
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";
const store = configureStore({
reducer: rootReducer,
});
export default store;
我在我的文件中使用了它,但它有一些错误
import { reducer } from 'app/reducers'
const codeState = useSelector((state: reducer) => state.code)
const code = codeState.codeOTP; // wrong here
const token = codeState.token; // and here
这个错误是
Property 'codeOTP' does not exist on type 'Reducer<{ codeOTP: string; token: string; }, AnyAction>'.
我不知道为什么会这样,我有 console.log(codeState) 但它是一个对象
答案 0 :(得分:0)
您的问题来自此处的误解。
const rootReducer = {
code: codeSlice
};
export type reducer = typeof rootReducer;
{code: codeSlice}
是一个 reducer 映射对象。它是一个对象,将状态的属性映射到它们各自的减速器。它不是减速器。减速器是一个 function
。
JavaScript 方面一切正常,因为 configureStore
can accept ReducersMapObject
用于 reducer
属性。但是您在基于它的打字稿类型方面遇到了问题。
Redux-toolkit 导出一些您可以使用的有用的实用程序类型。请注意,您想要的 useSelector
类型是 state 的类型,而不是 reducer。
import codeSlice from 'app/slices/codeSlice';
import { StateFromReducersMapObject } from "@reduxjs/toolkit";
// a reducer map object
const rootReducer = {
code: codeSlice
};
// the state for this reducer map
export type State = StateFromReducersMapObject<typeof rootReducer>;
export default rootReducer;
此类型 State
的计算结果为:
type State = {
code: {
codeOTP: string;
token: string;
};
}