我正在将 React 18 与 Redux 8 和 Typescript 结合使用。我想创建一个组件,允许调用者传入其中一个参数,但其他两个参数是从状态派生的。所以我创建了这个文件...
type OrderItemComponentProps = {
contact: Contact | undefined;
isAuthenticated: boolean;
orderItem: OrderItem;
}
const OrderItemComponent: React.FC<OrderItemComponentProps> = ({ contact, isAuthenticated, orderItem }) => {
...
}
function mapStateToProps(state: RootState, ownProps: OrderItemComponentProps): OrderItemComponentProps {
return {
contact: ownProps.contact, // passed as a prop to the container
isAuthenticated: state.auth.isAuthenticated, // derived from Redux state
orderItem: state.orderItem.orderItem // derived from Redux state
}
}
export const OrderItemContainer = connect(mapStateToProps)(OrderItemComponent)
在一个单独的文件中,我使用以下命令调用上面的内容
<OrderItemContainer contact={orderItem.sender} />
但这会产生 Typescript 错误
Type '{ contact: Contact | undefined; }' is missing the following properties from type '{ contact: Contact | undefined; isAuthenticated: boolean; orderItem: OrderItem; context?: Context<ReactReduxContextValue<any, AnyAction>> | undefined; store?: Store<...> | undefined; }': isAuthenticated, orderItem
输入“mapStateToProps”函数的正确方法是什么,以便正确允许声明此组件?
不幸的是,
connect
的类型定义很奇怪。解决此问题的最直接方法是在从 mapStateToProps
和父级 props
返回的内容之间拆分类型定义。幸运的是,ReturnType
允许您推断 mapStateToProps
的界面。然后使用类型转换强制生成的组件只需要父 props,即 contact
。它应该看起来像这样
type OrderItemComponentProps = {
contact: Contact | undefined;
}
const OrderItemComponent: React.FC<OrderItemComponentProps & ReturnType<typeof mapStateToProps> = ({ contact, isAuthenticated, orderItem }) => {
return null
}
function mapStateToProps(state: RootState) {
return {
isAuthenticated: state.auth.isAuthenticated, // derived from Redux state
orderItem: state.orderItem.orderItem // derived from Redux state
}
}
export const OrderItemContainer = connect(mapStateToProps)(OrderItemComponent) as React.FC<OrderItemComponentProps>