【问题标题】:Typescript: How to type combined reducers?Typescript:如何键入组合减速器?
【发布时间】:2020-02-19 18:42:22
【问题描述】:

我正在将我的小型 React Native 项目从纯 Javascript 迁移到 Typescript。虽然到目前为止进展顺利,但我现在遇到了 Redux 的问题。

我遇到的减速器是radioButtonSelectedReducer。在应用程序中,有两个单选按钮。如果单击第一个,则给出字符串“itemOne”,如果单击第二个,则给出字符串“itemTwo”。因此,radioButtonSelected 必须是字符串类型,我想。但它给出了错误:radioButtonSelected: string; -->

"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'" 

我是一个 Typescript 新手,不知道如何处理这条消息。

imports ...

export interface IApplicationState {
  radioButtonSelected: string;
  searchBarInput: string;
  searchBarResult: string;
}

const rootReducer = combineReducers<IApplicationState>({
  radioButtonSelected: radioButtonSelectedReducer,
  searchBarInput: searchBarInputReducer,
  searchBarResult: searchBarResultReducer,
});

export type RootState = ReturnType<typeof rootReducer>; 

当我在没有&lt;IApplicationState&gt; 的情况下离开combineReducers() 并在mapStateToProps() 中调用RootState 时,会出现错误:

  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.

这是实现单选按钮的组件中的 sn-p:

...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}

【问题讨论】:

    标签: typescript redux react-redux


    【解决方案1】:

    您不必声明IApplicationState 或将其作为泛型传递给combineReducers()。事实上,这正是type RootState = ReturnType&lt;typeof rootReducer&gt; 的意义所在。它推断组合状态类型是什么,因此您不必声明它或不断更新它。

    详情请咨询the Redux docs page on "Usage with TypeScript"

    【讨论】:

    • 感谢您的回复。我在第一次运行时就尝试过这个,但是当我在组件中调用 mapStateToProps 时,它说:错误 TS2339:Property 'itemSelected' does not exist on type 'CombinedState'。更新了我的问题。
    • 这是因为您没有将名为 itemSelected 的字段传递给 combineReducers。要么是您忘记将另一个减速器添加到根减速器,要么您的字段名称不匹配(即,state.itemSelected 实际上应该是 state.radioButtonSelected)。
    猜你喜欢
    • 2017-02-26
    • 2021-03-08
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2020-07-07
    • 2018-09-18
    相关资源
    最近更新 更多