获取 redux 状态的类型



我想获得一个redux状态的类型,它将用于模拟所述状态。

到目前为止,我发现我有这个减速器:

(alias) const reducer: {
selectedElement: Reducer<StructureElement, AnyAction>;
fetchedState: Reducer<FetchedState, AnyAction>;
... 10 more ...;
mesApi: Reducer<...>;
}

所以我想做的是,以某种方式从Reducer</here/, AnyAction>;部分的内部获得StructureElementFetchedState等等。

我怎样才能做到这一点?

或者有更好的方法来获得组合状态类型吗?但它必须自动完成。当它应该是自动生成的时候,我不想在两个地方更改类型。

如果我尝试这个:

type State = typeof reducer;

我得到

类型"{selectedElement:Reducer<StructureElement,AnyAction>;fetchedState:Reducer<fetchedState,AnyAction>;…还有10个…;mesApi:Reducer<…>}"不可分配给类型";钥匙?:一串type:StateType;}。。。还有11个。。。;mesApi?:{…;};}'。属性"selectedElement"的类型不兼容。

这很有道理。

好吧,我太笨了。我从基本设置中得到了这样的东西:

export type RootState = ReturnType<typeof store.getState>;

它似乎起到了作用。

我建议简单地对其进行显式建模,然后在需要的地方导入这些类型:

export type UserState = {
readonly isLoggedIn: boolean;
// other user state here
};
// Type for entire global redux state
export type AppState = {
users: UserState;
// other sub-states here
};

我亲自为我的状态中想要的每个功能创建一个切片,然后我有一个文件,我将首先在其中声明和导出我的RootState类型,然后我将组合我的所有缩减器。

export interface RootState {
pokemon: pokemonState;
pokemonTrainer: pokemonTrainerState;
}
const reducer = combineReducers<RootState>({
pokemon: pokemonSLice,
pokemonTrainer: pokemonTrainerSlice,
});

其中pokemonStatepokemonTrainerState是每个特征的类型。
然后我将在任何需要的地方使用RootState

最新更新