我正在为我当前的Typescript React项目使用Redux,并且很难进入它。到目前为止,连接组件对我来说还算不错。
interface OwnProps {
ownProp?: boolean;
}
interface PropsFromState {
stateProp: any;
}
interface PropsFromDispatch {
dispatchProp: (...) => void;
}
type MyComponentProps = OwnProps & PropsFromState & PropsFromDispatch;
class MyComponent extends React.Component<MyComponentProps> {...}
const mapStateToProps = ({ componentState }: IAppState, ownProps: OwnProps): PropsFromState => {
return {
stateProp: componentState.stateProp,
ownProp: ownProps.ownProp,
};
};
const mapDispatchToProps = (dispatch: any): PropsFromDispatch => {
return {
dispatchProp: (...) => dispatch(dispatchProp(...))
};
};
export default connect<PropsFromState, PropsFromDispatch, OwnProps>(
mapStateToProps,
mapDispatchToProps
)(MyComponent);
尽管最近我尝试在连接的组件上放置引用,但发现必须启用forwardRef
选项。所以我将连接呼叫更新为
export default connect<PropsFromState, PropsFromDispatch, OwnProps>(
mapStateToProps,
mapDispatchToProps,
null,
{ forwardRef : true }
)(MyComponent);
但是因为我不得不在mergedProps
之间插入第三个参数(我认为可以将其默认为null
,所以没有问题),所以tslint
现在对我抛出错误尝试渲染组件,说类似
<MyComponent ownProp ref={ref => this.comp = ref}/>
Type '{ ownProp: true; ref: (ref: Component<Pick<MyComponent, "ownProp" | "stateProp" | "dispatchProp"> & OwnProps, any, any>) => Component<...>; }' is missing the following properties from type 'Readonly<Pick<MyComponentProps, "ownProp" | "stateProp" | "dispatchProp"> & OwnProps>': stateProp, dispatchProp - ts(2739)
似乎组件现在需要其他不需要的道具。知道如何处理吗?