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泛型和参数的知识,特此为记。