[英]Property does not exist on type '{}'
我正在嘗試在我的 React 應用程序中使用 Typescript
在我的mapStateToProps
我有這個代碼
const mapStateToProps = (state: AppState) => {
console.log(state)
return {
...state.player,
position: state.player.position
}
}
我的應用狀態
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
TypeScript error: Property 'player' does not exist on type '{}'. TS2339
就行...state.player
但是如果我在console.log 狀態(在那之前的那一行)我的state
有player
屬性。
我不確定為什么會收到此錯誤。 所有的幫助將不勝感激。
播放器減速器
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;
問題是combineReducers
無法推斷您傳入的對象的類型, as any
。 這意味着您的根減速器只能通過類型推斷:
const rootReducer: Reducer<{}, AnyAction>;
只需取出combineReducers
的as any
:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.