reactjs - React Recompose 在 Props 上导致 Typescript 错误
问题描述
我有一个非常基本的有状态组件,我使用 recompose 将多个 HOC 添加到我的组件中(在我的示例中,为了简单起见,我只使用一个)。出于某种原因,打字稿给了我一个关于我的道具进入我的组件的错误。我怎样才能摆脱这个错误?
这是我的代码:
import * as React from 'react';
import { connect } from 'react-redux';
import { compose } from 'recompose';
interface IStoreState {
readonly sessionState: {
authUser: { email: string; }
}
}
interface IAccountPageProps {
authUser: { email: string }
}
const AccountPage = ({ authUser }: IAccountPageProps ) =>
<div>
<h1>Account: {authUser.email}</h1>
</div>
const mapStateToProps = (state: IStoreState) => ({
authUser: state.sessionState.authUser,
});
export default compose(
connect(mapStateToProps)
)(AccountPage);
我得到的错误是:
Argument of type '({ authUser }: IAccountPageProps) => Element' is not assignable to parameter of type 'ComponentType<{}>'.
Type '({ authUser }: IAccountPageProps) => Element' is not assignable to type 'StatelessComponent<{}>'.
Types of parameters '__0' and 'props' are incompatible.
Type '{ children?: ReactNode; }' is not assignable to type 'IAccountPageProps'.
Property 'authUser' is missing in type '{ children?: ReactNode; }'.
如果我不使用 recompose 而是写
export default connect(mapStateToProps)(AccountPage)
我没有收到任何错误。
解决方案
当前的打字compose
是非常没用的。如果要使用compose
,则必须props
手动指定原始组件和最终组件的类型,并且不会检查您指定的类型是否与您传递的高阶组件列表匹配:
export default compose<IAccountPageProps, {}>(
connect(mapStateToProps)
)(AccountPage);
我建议不要compose
在 TypeScript 中使用。
推荐阅读
- javascript - 我的浏览器无法读取 addEventListener 的属性是否有原因?
- stm32 - STM32H7 - IAR 将局部变量放入“保留内存”(0x1FF20000 - 0x1FFFFFFF)
- java - Java ASM MethodVisitor 的方法不被 ClassVisitor 调用
- java - 如何在java中读取文本文件输入并将其加载到xml格式的FTL模板
- python - spritecollide() 未按预期运行
- python - 为什么此列表中两个字母的索引返回相同?
- javascript - 使用 OwlCarousel 加载照片循环时出现问题
- rust - 具有特征的通用 API
- javascript - 每个用户是否只有 1 个会话 ID?
- java - 如何使用 ClassVisitor / Java Bytecode (ASM) 向 ByteCode 中的方法添加额外指令