我使用 React + Redux Toolkit + Typescript。
减速器看起来像这样:
import { createSlice } from '@reduxjs/toolkit';
interface IRootState {
test: boolean;
}
const initialState: IRootState = {
test: true,
};
export const mainReducer = createSlice({
name: 'mainReducer',
initialState,
reducers: {
testSwitcher(state) {
state.test = !state.test;
},
},
});
export const { testSwitcher } = mainReducer.actions;
export default mainReducer.reducer;
商店看起来像这样:
const store = configureStore({
reducer: {
main: mainReducer,
},
devTools: process.env.NODE_ENV !== 'production',
});
在组件中导入状态:
const { test } = useSelector((state) => state.main);
结果,typescript 在 state.main 中显示错误:
“DefaultRootState”类型上不存在属性“main”
如何解决?
您需要为状态(创建商店的位置)添加一个类型:
并在选择器中指示状态属于这种类型 - 然后打字稿将知道
state有一个对象main:https://react-redux.js.org/using-react-redux/usage-with-typescript#define-root-state-and-dispatch-types