TS2339:“DefaultRootState”类型上不存在属性“tsReducer”

新手上路,请多包涵

为上述问题而苦苦挣扎。看到类似的问题,但无法弄清楚。

下面的代码是我第一次尝试在使用 .js 和 .jsx 的现有 React 项目中使用 TypeScript 打开和关闭对话框。

 import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import {useDispatch, useSelector} from 'react-redux';
import {closeTsDialog} from '../actions/tsDialog'
import {ActionTypes} from '../actions/types';

const TsApp = (): JSX.Element => {
    const dispatch = useDispatch();

// ERROR SHOWS UP ON LINE BELOW "state?.tsReducer?.isDialogOpen"
    const isDialogOpen = useSelector(state => state?.tsReducer?.isDialogOpen);
    const state = useSelector(s => s);
    console.log('->>>>>> state', state);

    // main tsx excluded to allow for posting on stackoverflow
};

export default TsApp;

 import {TsDialogAction} from "../actions/tsDialog";

const initialState = {
    id: 0,
    isDialogOpen: false
};

const tsReducer = (state: TsDialogAction = initialState, action: Action) => {
    switch (action.type) {
        case ActionTypes.closeDialog: {
            return {...state, isDialogOpen: false};
        }
        case ActionTypes.openDialog: {
            return {...state, isDialogOpen: true};
        }
        default:
            return state;
    }
};

export default tsReducer;

从’./types’导入{ActionTypes};

导出接口 TsDialogAction { isDialogOpen: boolean number: number }

导出接口 CloseTsDialog { 类型:ActionTypes.closeDialog 有效负载:TsDialogAction }

导出接口 OpenTsDialog { 类型:ActionTypes.openDialog 有效负载:TsDialogAction }

导出接口增量 { 类型:ActionTypes.increment 有效负载:TsDialogAction }

导出接口减量{类型:ActionTypes.减量负载:TsDialogAction}

export const closeTsDialog = (id: number) => ({type: ActionTypes.closeDialog, payload: id}); export const openTsDialog = (id: number) => ({type: ActionTypes.openDialog, payload: id}); export const incrementAction = (id: number) => ({type: ActionTypes.increment, payload: id}); export const decrementAction = (id: number) => ({type: ActionTypes.decrement, payload: id});

原文由 fullStackRyan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

它在抱怨类型。快速解决方案是添加 any 作为状态类型。

正确的解决方案需要以下两个步骤:

  1. 在 Root Reducer 中创建 RootState 类型。
 export const rootReducer = combineReducers({
  dashboard: dashboardReducer,
  user: userReducer
});

export type RootState = ReturnType<typeof rootReducer>

  1. 为状态对象提供 RootState 类型。
   let userData = useSelector((state: RootState) => {
    return state.user.data;
  });

原文由 Yuvraj Patil 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进