类型“{}”上不存在属性

问题描述 投票:2回答:1

我正在尝试在我的React应用程序中使用Typescript

在我的mapStateToProps我有这个代码

const mapStateToProps = (state: AppState) => {
    console.log(state)
    return {
        ...state.player,
        position: state.player.position
    }
}

我的AppState

import { combineReducers } from 'redux';
import playerReducer from './player';

export const rootReducer = combineReducers({
  player: playerReducer
} as any);

export type AppState = ReturnType<typeof rootReducer>

而且我得到一个关于TypeScript error: Property 'player' does not exist on type '{}'. TS2339线的错误...state.player但是如果我控制台.log状态(在那之前的那一行)我的stateplayer属性。

我不知道为什么我会收到这个错误。所有的帮助将不胜感激。

球员减速机

import { Action } from '../actions/types';
import { Store } from '../types';


export const initialState: Store = {
  position: [410, 0]
};


const playerReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'MOVE_PLAYER':
      return {
        ...state,
        position: action.payload
      }   
    default:
      return state;
  }
}

export default playerReducer;
reactjs typescript
1个回答
1
投票

问题是由于combineReducersas any无法推断出你传入的物体的类型。这意味着您的根reducer只能按类型推断:

const rootReducer: Reducer<{}, AnyAction>;

只需在as any中取出combineReducers

export const rootReducer = combineReducers({
  player: playerReducer
});

应该推断为:

const rootReducer: Reducer<{
  player: PlayerState;
}, AnyAction>;

尝试强力输入你的playerReducer

import { Action, Reducer } from "redux";

const playerReducer: Reducer<Store, Action> = (state = initialState, a) => {
    ...
};

我在我的项目中使用的确切模式将是这样的(当然,你可能想要调整它,直到你得到一些更适合你的项目的东西):

import { Action, Reducer } from "redux";
import { MOVE_PLAYER } from "../actions/playerActions"; // list all relevant actions here

export interface PlayerState {
  readonly position: [number, number];
}

const initialState: PlayerState = {
  position: [410, 0];
};

const reducers: { [k: string]: (s: PlayerState, a: any) => PlayerState } = {
  [MOVE_PLAYER]: (s, a: { payload: [number, number] }) => ({ ...s, position: a.payload }),
  // other player reducers
}

const reducer: Reducer<PlayerState, Action> = (s = initialState, a) => {
  const f = reducers[a.type];
  return typeof f === "function" ? f(s, a) : s;
};
export default reducer;
© www.soinside.com 2019 - 2024. All rights reserved.