IT이야기

TS2339: 속성 'tsReducer'가 'DefaultRootState' 유형에 없음

cyworld 2022. 3. 21. 08:56
반응형

TS2339: 속성 'tsReducer'가 'DefaultRootState' 유형에 없음

위의 질문에 고심하고 있다.비슷한 질문을 보았지만 알아낼 수 없다.

아래 코드는 내가 .js와 .jsx를 사용하는 기존 리액션 프로젝트에서 처음으로 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;

{Action} 가져오기'./type'의 유형};

내보내기 인터페이스 TsDialogAction { isDialogOpen: 부울 번호: 숫자 }

내보내기 인터페이스 CloseTsDialog { 유형:ActionTypes.closeDialog 페이로드:TsDialogAction }

내보내기 인터페이스 OpenTsDialog { 유형:ActionTypes.openDialog 페이로드:TsDialogAction }

내보내기 인터페이스 증분 { 유형:ActionTypes.증가 페이로드:TsDialogAction }

내보내기 인터페이스 감소 { 유형:ActionTypes.decretion payload:TsDialogAction }

내보내기 const closeTsDialog = (id: number) =>({type:ActionTypes.closeDialog, payload: id}; 내보내기 constitute OpenTsDialog = (id: number) =>({type:ActionTypes.openDialog, payload: id}; 내보내기 constitutionAction = (id: number) =>({type:ActionTypes.crement, payload: id}; 내보내기 항상 감소작용 = (id: number) =>({type:ActionTypes.dreamment, payload: id};

그것은 그 유형에 대해 불평하고 있다.빠른 솔루션이 추가될 수 있음any주형으로

적절한 솔루션은 다음 두 단계를 거쳐야 한다.

  1. RootReducer에서 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;
  });

당신은 그 타입을 신고해야 한다.state선택기 내의 인수(예:

const isDialogOpen = useSelector( (state: RootState) => state.tsReducer.isDialogOpen);

예제는 TypeScript 사용 Redex 문서정적 입력 Resact-Redex 문서 페이지를 참조하십시오.

(또한, 스타일리쉬한 노트로서: 제발 그렇게 부르지 마십시오.tsReducer당신의 뿌리 상태로.취급하는 데이터와 일치하는 이름(예:state.ui.)

리액션 리플렉스를 사용하는 경우 즉시 사용할 수 있는 또 다른 용액은RootStateOrAny.

import { RootStateOrAny, useSelector } from 'react-redux';

// and then use it like so in your component
...
const authState = useSelector((state: RootStateOrAny) => state.auth);
...


나에게 있어 selector는 사용 상태를 지정하는 것보다 더 나은 해결책은 아래와 같을 것이다.
이전과 같이node_modules/@types/react-redux/index.d.ts모듈 증강을 사용할 수 있다.

/**
 * This interface can be augmented by users to add default types for the root state when
 * using `react-redux`.
 * Use module augmentation to append your own type definition in a your_custom_type.d.ts file.
 * https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
 */
// tslint:disable-next-line:no-empty-interface
export interface DefaultRootState {}

아래와 같이 하십시오.

  1. 감속기로 AppState 내보내기src/reducer/index.ts
const reducers = combineReducers({
  userReducer,
});

export type AppState = ReturnType<typeof reducers>;
  1. 새로 만들기your_custom_type.d.ts. (reaction-remedx.d.ts가 더 좋다.)
    src/@types/your_custom_type.d.ts
import 'react-redux';

import { AppState } from '../reducers';

declare module 'react-redux' {
  interface DefaultRootState extends AppState { };
}
  1. 추가하다typeRootstsconfig.json으로
{
  "compilerOptions": {
    ...
    "typeRoots": ["src/@types"]
  }
}

AppState를 지정하지 않고 아래와 같이 사용할 수 있음

import React, { memo } from 'react';
import { useSelector } from 'react-redux';

export default memo(() => {
  const isLoggedIn = useSelector(
    ({ userReducer }) => userReducer.isLoggedIn
  );
  return <div>{isLoggedIn}</div>;
});

이것들은 유용한 물건이다.

  1. https://redux.js.org/recipes/usage-with-typescript#define-root-state-and-dispatch-types
  2. https://redux.js.org/recipes/usage-with-typescript#define-typed-hooks

그래서 먼저 정의를 내리십시오.RootState그리고AppDispatch다음과 같다:

//at store/index.ts
const rootReducer = combineReducers({
  tsReducer: tsReducer
});
const store = createStore(rootReducer)

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

그런 다음 후크를 정의하십시오.useAppDispatchuseAppSelector은 요소에 할 수 는 구성 요소에 사용할 수 있다.

//at store/hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './'

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

그리고 다음과 같은 구성 요소에 사용하십시오.

import {useAppSelector} from '../store/hooks'
//...
const TsApp = (): JSX.Element => {
    const dispatch = useDispatch();

// ERROR should be fixed
    const isDialogOpen = useAppSelector(state => state.tsReducer.isDialogOpen);
};

참조URL: https://stackoverflow.com/questions/60777859/ts2339-property-tsreducer-does-not-exist-on-type-defaultrootstate

반응형