Reactjs 属性不存在于类型';{}';
我正在尝试在我的React应用程序中使用Typescript 在myReactjs 属性不存在于类型';{}';,reactjs,typescript,Reactjs,Typescript,我正在尝试在我的React应用程序中使用Typescript 在myMapStateTrops中,我有以下代码 const mapStateToProps = (state: AppState) => { console.log(state) return { ...state.player, position: state.player.position } } 我的AppState import { combineReducer
MapStateTrops
中,我有以下代码
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>
问题在于,
combinereducer
无法推断您传入的对象的类型,因为与任何
一样。这意味着您的根减速器只能按类型推断为:
const rootReducer: Reducer<{}, AnyAction>;
应推断为:
const rootReducer: Reducer<{
player: PlayerState;
}, AnyAction>;
我在项目中使用的确切模式如下所示(当然,您可能希望对其进行调整,直到获得对您的项目更有效的模式):
从“redux”导入{Action,Reducer};
从“./actions/playerActions”//导入{MOVE_PLAYER}在此列出所有相关操作
导出接口PlayerState{
只读位置:[编号,编号];
}
常量initialState:PlayerState={
职位:[410,0];
};
常量缩减器:{[k:string]:(s:PlayerState,a:any)=>PlayerState}={
[MOVE_PLAYER]:(s,a:{payload:[number,number]})=>({…s,position:a.payload}),
//其他玩家减速器
}
const reducer:reducer=(s=初始状态,a)=>{
常数f=减速机[a.type];
返回类型f==“函数”?f(s,a):s;
};
导出默认减速机;
现在我;我在第player:playerReducer
行中出错TypeScript错误:Type'(state:Store | undefined,action:ActionA)=>Store |{position:string;}'不能分配给类型“Reducer”。参数“state”和“state”的类型不兼容。类型“Store |{position:string;}| undefined”不能分配给类型“Store | undefined”。类型“{position:string;}”不能分配给类型“Store”。属性“位置”的类型不兼容。
export const rootReducer = combineReducers({
player: playerReducer
});
const rootReducer: Reducer<{
player: PlayerState;
}, AnyAction>;
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;