问题描述
当我使用 react 和 redux 时。 connect
方法会导致以下 tslint 警告/错误(我也不是 100% 确定此语句)。组件可以工作,但查看 tslint 错误让我很沮丧。
类型定义是这个interface IPrivateMenuItem extends StateProps,IMenuItem,IOwnProps {}
输入 '{ children: string;图标:“用户”;到:字符串; }' 不可分配到类型 'IntrinsicAttributes & Pick
我尝试了像 const PrivateMenuItem: React.FC<IPrivateMenuItem>
这样的组件定义。但是没有机会警告消失了。除非我删除连接语句。由于 redux 要求,这是不可能的。
然后,我将功能组件的 prop 类型切换为 IPrivateMenuItem,如下所定义。那么问题就没有了。我的问题是这是最佳做法还是有更简单的做法?
interface IPrivateMenuItem extends StateProps,React.PropsWithChildren<IOwnProps> {}
interface IOwnProps {
hasAnyAuthorities?: string[];
}
interface IPrivateMenuItem extends StateProps,React.PropsWithChildren<IOwnProps> {}
const PrivateMenuItem = ({ isAuthorized,id,to,icon,children }: IPrivateMenuItem) => {
return isAuthorized ? (
<MenuItem id={id} to={to} icon={icon}>
{children}
</MenuItem>
) : (
<></>
);
};
const mapStatetoProps = ({ authentication: { account } }: IRootState,{ hasAnyAuthorities = [] }: IOwnProps) => ({
isAuthorized: hasAnyAuthority(account.authorities,hasAnyAuthorities),});
type StateProps = ReturnType<typeof mapStatetoProps>;
export default connect(mapStatetoProps)(PrivateMenuItem);
解决方法
没有看到整个组件有点困难,但如果它有帮助
连接的完整输入如下
connect<TheMapStateToPropsType,TheDispatchToPropsType,TheComponentPropsType,TheStorePropsType>
你可以像这样输入你的组件:(我用一个类来做,但你得到了一个功能组件的精神)
interface OwnProps { }
interface StateProps { }
interface DispatchProps { }
type Props = OwnProps & StateProps & DispatchProps;
export class MyComponent extends Component<Props> { }
const mapStateToProps = (state): StateProps => ({
})
const mapDispatchToProps = (dispatch): DispatchProps => {
return {
}
}
export default connect<StateProps,DispatchProps,OwnProps,StorePropsIfYouWant>(mapStateToProps,mapDispatchToProps)(MyComponent)