gpt4 book ai didi

Typescript:如何输入组合 reducer ?

转载 作者:行者123 更新时间:2023-12-02 02:59:31 26 4
gpt4 key购买 nike

我正在将我的小型 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/

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