gpt4 book ai didi

reactjs - 类型 '{}' 上不存在属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:33 24 4
gpt4 key购买 nike

我正在尝试在我的 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 错误:属性“player”在类型“{}”上不存在。 TS2339 与行 ...state.player 相关但是如果我 console.log 状态(在那之前的那一行)我的 stateplayer 属性。

我不确定为什么会收到此错误。我们将不胜感激。

玩家 reducer

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>;

简单地取出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) => {
...
};

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

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;

关于reactjs - 类型 '{}' 上不存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55636963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com