我正在尝试在我的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状态(在那之前的那一行)我的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
无法推断出你传入的物体的类型。这意味着您的根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;