您好,我正在尝试创建useSelectors
钩子,该钩子与useSelector
基本相同,但是它应该接收对象并返回对象。到目前为止,我可以正确键入所有键,但是值传递不正确。
这是我的代码:
// useSelector.ts
const useSelectors = < U extends {} > (
selectors: {
[K in keyof U]: (state: Redux) => TypedUseSelectorHook < Redux > | null
},
): { [K in keyof U]: TypedUseSelectorHook<Redux> | null } => {
return reduce(
selectors,
(acc, selector, key) => {
return { ...acc,
[key]: useSelector(selector)
};
}, {},
);
};
// Component.tsx
const Component = () => {
const {
loading,
hierarchy,
error
} = useSelectors({
loading: selectHierarchyLoading,
hierarchy: selectHierarchyData,
error: selectHierarchyError,
})
return ...;
}
IDE知道类型,因为它让我大叫我无法将这些类型分配给TypedUseSelectorHook
,但我不知道如何传递它们,知道吗? :)
答案 0 :(得分:0)
经过一番尝试,我使它成功了,如果有人会对接收选择器对象并返回值对象的钩子感兴趣。
const useSelectors = < SelectorMap extends {} > (
selectors: {
[Selector in keyof SelectorMap]: (state: Redux) => SelectorMap[Selector]
},
): {
[Selector in keyof SelectorMap]: SelectorMap[Selector]
} => {
return reduce(
selectors,
(acc, selector, key) => {
return { ...acc,
[key]: useSelector(selector)
};
}, {}
as {
[Selector in keyof SelectorMap]: SelectorMap[Selector]
},
);
};