如何解决创建可重用的Redux连接器具有相同的mapState和mapDispatch-遇到TypeScript问题
这里是可以选择呈现字符串(未连接到Redux存储)或选择框的组件。
export function Content(props: ContentProps) {
const { language } = props;
if (!props.setLanguage) {
return (
<div>{language}</div>
);
}
return (
<Select
language={language}
languages={languages}
onChange={e => {
props.setLanguage!(e.target.value);
}}
/>
);
}
此代码可以正常运行
const mapStateToProps = (state: RootState) => ({
language: state.language,});
const mapDispatch = {
setLanguage,};
const connector = connect(mapStateToProps,mapDispatch);
const ConnectedContent = connector(Content);
function App() {
return (
<ConnectedContent />
);
}
但是问题是我需要其他增强功能,因此连接器必须可重用,例如
//type PropsFromRedux = ConnectedProps<typeof connector>;
interface LoadingProps {
loading?: boolean;
}
const withLoading = <P extends {}>(Component: React.ComponentType<P>) => (props: P & LoadingProps) => (
<>
{props.loading && <div>Loading</div>}
<Component {...props as P} />
</>
);
function getConnectedComponent(Component: React.ComponentType) {
const ComponentWithLoading = withLoading(Component);
return connector(ComponentWithLoading);
}
const ConnectedContent = getConnectedComponent(Content);
但是我不知道如何正确地将类型/泛型添加到getConnectedComponent函数中。通过推断我得到了
Error:(24,48) TS2345: Argument of type '(props: ContentProps) => Element' is not assignable to parameter of type 'ComponentType<{}>'.
Type '(props: ContentProps) => Element' is not assignable to type 'FunctionComponent<{}>'.
Types of parameters 'props' and 'props' are incompatible.
Property 'language' is missing in type '{ children?: ReactNode; }' but required in type 'ContentProps'.
工作示例在https://codesandbox.io/s/elegant-snowflake-b5r89上 还要推送到GitHub https://github.com/hitrov/reusable-redux-connector
解决方法
我不确定“连接器应该可重用”是什么意思,或者您所指的是“其他增强功能”。它已经可以重用了。从connect(mapState,mapDispatch)
返回的函数已准备好接受您传入的任何组件,因此它已经已经完成了您的概念getConnectedComponent
想要做的事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。