Typescript:如何输入组合 reducer ?

标签 typescript redux react-redux

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

我正在努力解决的 reducer 是 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>; 

当我离开时combineReducers()没有<IApplicationState>并调用RootStatemapStateToProps() ,它给出了错误:

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

以下是实现单选按钮的组件的代码片段:

...

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

最佳答案

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

请引用the Redux docs page on "Usage with TypeScript"了解更多详情。

关于Typescript:如何输入组合 reducer ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307199/

相关文章:

javascript - redux 和状态机(例如 xstate)之间的实际区别是什么?

react-native - 什么时候不应该在 React-Native 中使用 Redux?

javascript - Redux 和 React 路由器 : Combing dispatch and navigation (history. 推送)

node.js - Typescript2 路径模块解析

reactjs - 如何在 react 中从 reducer 状态添加和删除项目

typescript - 如何为具有动态键的对象定义接口(interface)?

javascript - 需要使用react-redux更新无状态组件的状态

javascript - React Redux 调试 Prop

javascript - 在 Angular 2 组件内的 javascript 中访问 Typescript 变量值

css - 如何调整mat-option的位置