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

ful*_*yan 29 typescript reactjs redux

纠结上面的问题。看到类似的问题,但无法弄清楚。

下面的代码是我第一次尝试在使用 .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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

export interface Increment { type: ActionTypes.increment payload: TsDialogAction }

export interface Decrement { type: ActionTypes.decrement payload: 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});

Yuv*_*til 46

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

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

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

export type RootState = ReturnType<typeof rootReducer>
Run Code Online (Sandbox Code Playgroud)
  1. 为状态对象提供 RootState 类型。
  let userData = useSelector((state: RootState) => {
    return state.user.data;
  });
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是最好的答案,谢谢@Yuvraj (2认同)

mar*_*son 26

您需要state在选择器中声明参数的类型,例如:

const isDialogOpen = useSelector( (state: RootState) => state.tsReducer.isDialogOpen);
Run Code Online (Sandbox Code Playgroud)

请参阅有关 TypeScript 用法Redux 文档,以及有关静态类型React-Redux 文档页面以获取示例。

(另外,作为文体说明:请不要tsReducer在您的根状态中调用它。给它一个与它正在处理的数据相匹配的名称,例如state.ui。)


Thu*_*San 13

对我来说,比在 useSelector 中指定状态更好的解决方案如下。
在 中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 {}
Run Code Online (Sandbox Code Playgroud)

做如下

  1. 在 reducer 中导出 AppState src/reducer/index.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 {}
Run Code Online (Sandbox Code Playgroud)
  1. 创建新的your_custom_type.d.ts. (我更喜欢 react-redux.d.ts)。
    src/@types/your_custom_type.d.ts
const reducers = combineReducers({
  userReducer,
});

export type AppState = ReturnType<typeof reducers>;
Run Code Online (Sandbox Code Playgroud)
  1. typeRoots在 tsconfig.json 中添加
import 'react-redux';

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

declare module 'react-redux' {
  interface DefaultRootState extends AppState { };
}
Run Code Online (Sandbox Code Playgroud)

您可以在不指定 AppState 的情况下使用如下

{
  "compilerOptions": {
    ...
    "typeRoots": ["src/@types"]
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 优雅的解决方案! (2认同)

the*_*mer 11

如果您使用的是 react-redux,另一个开箱即用的解决方案是使用RootStateOrAny.

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

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


Run Code Online (Sandbox Code Playgroud)


小智 7

这些都是有用的文章。

  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
Run Code Online (Sandbox Code Playgroud)

然后定义可以在组件中使用的钩子( useAppDispatch, )。useAppSelector

//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
Run Code Online (Sandbox Code Playgroud)

并在组件上使用它,如下所示:

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

// ERROR should be fixed
    const isDialogOpen = useAppSelector(state => state.tsReducer.isDialogOpen);
};
Run Code Online (Sandbox Code Playgroud)


cod*_*itu 6

这对我有用

import { RootStateOrAny, useSelector } from "react-redux"

const search = useSelector((state: RootStateOrAny) => state.searchObj.values)
Run Code Online (Sandbox Code Playgroud)

在非 React 组件中,您只能执行函数或钩子操作

import {store} from "../redux/store"

const search: SearchProps | any = store.getState().searchObj.values
Run Code Online (Sandbox Code Playgroud)