react-router中connect 的泛型和参数

本文详细介绍了在使用typescript和react-router时,connect函数的参数及其泛型用法。包括mapStateToProps和mapDispatchToProps的作用,以及mergeProps和options选项的详细解释。同时,文章还探讨了connect泛型的含义,如TStateProps、TOwnProps等,帮助开发者更好地理解和使用connect。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react-router中的connect是连接redux和react组件的数据传输方式,在实际的项目中,typescript和connect联合开发时,connect的参数问题折腾了好久,下面整理的就是参数的具体含义。

connect的参数

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

connect接收四个参数mapStateToProps, mapDispatchToProps, mergeProps, options

  • mapStateToProps: 将redux store中的state映射到当前component, 我们可以在当前组件中使用this.props.stateName,如果没有,为undefined
  • mapDispatchToProps: 将redux 中的dispatch方法映射到当前component,如果没有,为undefined
  • mergeProps: 合并了上面两个属性的props,默认会assign(mapStateToProps, mapDispatchToProps),所以一般不写,但是如果在当前组件中有有自定义的属性,则需要声明
  • options: 可选,一般情况下不填,可以参考官网的描述

[options] (Object) If specified, further customizes the behavior of the connector.

  • [pure = true] (Boolean): If true, implements shouldComponentUpdate and shallowly compares the result of mergeProps, preventing unnecessary updates, assuming that the component is a “pure” component and does not rely on any input or state other than its props and the selected Redux store’s state. Defaults to true.
  • [withRef = false] (Boolean): If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. Defaults to false.

connect的泛型

connect的泛型根据参数的不同有不同的个数。

export declare function connect<TStateProps, TDispatchProps, TOwnProps>(
    mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps>,
    mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>
): ComponentDecorator<TStateProps & TDispatchProps, TOwnProps>;
export declare function connect<TStateProps, TDispatchProps, TOwnProps, TMergedProps>(
    mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps>,
    mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
    mergeProps: MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps>,
): ComponentMergeDecorator<TMergedProps, TOwnProps>;

如上面的例子中,第一个泛型TStateProps指的是当前组件头部声明的包含mapStateToProps中返回的props.比如:

interface AppStateProps {
	item: api.ItemDetail;
	component: 'rate' | 'rating' | 'rate_or_rating';
}

同理,第二个指的是mapDispatchToProps中返回的props

interface AppDispatchProps {
	activeProfile: boolean;
	userRating: number;
	isSignedIn?: boolean;
	onStateChanged?: (opened: boolean) => void;
}

第三个TOwnProps指的是该组件的所有props,通常情况下包含了AppStateProps和AppDispatchProps中的所有属性。如果包含了,前面两个props如果没有,可以声明为any.例如如下声明:

export default connect<any, any, AppProps>(mapStateToProps, mapDispatchToProps)(App);

以上就是关于connect泛型和参数的知识,特此为记。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值