键入mapStateToProps React Redux

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

我无法输入mapStateToProps的“ state”参数

如果我仅更改state : any而不是state: AppState,则它正常工作,没有错误。但我想为我的state参数输入正确的代码。

现在,我在connect()的mapStateToProps参数上遇到此错误

没有重载匹配此调用。最后一次重载给出了以下错误。类型'(state:{测验:IQuizInitialState;})=> StateProps'的参数不可分配给'MapStateToPropsParam'类型的参数。无法将类型'(state:{测验:IQuizInitialState;})=> StateProps'分配为'MapStateToPropsFactory'。参数“状态”和“初始状态”不兼容。类型“ {}”中缺少属性“测验”,但类型“ {{测验:IQuizInitialState; }'。ts(2769)

interface OwnProps {

}
interface StateProps {

}
interface DispatchProps {

}

type Props = OwnProps & StateProps & DispatchProps;


export class App extends Component<Props> {

  render() {
    return (
     <div>Hey</div>
    );
  }
}

const mapStateToProps = (state: AppState): StateProps => ({ 
})

const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, AnyAction>): DispatchProps => {
    return {
    }
}


// The args 'mapStateToProps' generate the error
export default connect<StateProps,DispatchProps,OwnProps>(mapStateToProps, mapDispatchToProps)(App)

这是我的rootReducer:

import { combineReducers } from 'redux';
import { QuizReducer } from './quiz';

const rootReducer = combineReducers({
    quiz: QuizReducer
});

export type AppState = ReturnType<typeof rootReducer>


export default rootReducer;

并且单个reducer是:

import { TYPES } from '../actions/action-types';
import { IQuizListItem, Action } from '../models/index';
import { AnyAction } from 'redux';


export interface IQuizInitialState {
    quizListItem: IQuizListItem[]
}
const quizInitialState: IQuizInitialState = {
    quizListItem: []
}
export const QuizReducer = (state = quizInitialState, action: AnyAction): IQuizInitialState => {
    switch (action.type) {
        case TYPES.getQuizListItems:
            return {
                ...state,
                quizListItem: (action as Action<IQuizListItem[]>).payload
            }

        default:
            return state
    }
}

谢谢你们!

reactjs typescript redux typing
1个回答
7
投票

您的州类型与整个州使用的类型相同。因为mapStateToProps将整个状态传递给选择器。在您的情况下,我认为这将是正确的类型IQuizInitialState

const mapStateToProps = (state: IQuizInitialState): StateProps => ({ 

})

编辑

在您的评论中,您提及IQuizInitialState不是您的整个应用程序状态。那么那不是您需要的那个。您需要整个应用程序状态的类型。为此,您可以为每个单个reducer类型(即您的IQuizInitialState)创建一个接口,但为其他reducer创建一个接口。

由于我没有您的代码库,但考虑到,因此我不得不在这里假设

combineReducers({potato: quizReducer, tomato: otherReduzer})

您需要输入类型

interface IApplicationState {
potato: IQuizInitialState;
tomato: IOTherInterfaceYouDefinedForThisReducer;
}

您的CombineReducers可能看起来像:

combineReducers<IApplicationState>({
  potato: quizReducer,
  tomato: otherReduzer
});

希望您能明白。

编辑2阅读您的最后一条评论后,我注意到您正在请求带有两个参数的mapStateToProps。而您只是定义一个。然后,您的连接泛型似乎是错误的。您应该考虑以下内容:

connect<StateProps, DispatchProps, Props, IApplicationState>

其中:

  • StateProps:描述mapStateToProps()返回的内容>
  • DispatchProps:描述dispatchToProps()返回的内容>
  • 道具:你的道具道具
  • [IApplicationState:代表您的Apps Redux整个状态
© www.soinside.com 2019 - 2024. All rights reserved.