首页 > 解决方案 > React & Redux tslint 警告

问题描述

当我使用 react 和 redux 时。该connect方法导致以下 tslint 警告/错误(我也不是 100% 确定该声明)。组件有效,但查看 tslint 错误让我很生气。

类型定义是这个interface IPrivateMenuItem extends StateProps, IMenuItem, IOwnProps {}

输入'{孩子:字符串;图标:“用户”;到:字符串;}' 不可分配给类型 'IntrinsicAttributes & Pick<IPrivateMenuItem, "hasAnyAuthorities" | “身份证” | “到” | “图标”> & IOwnProps'。'IntrinsicAttributes & Pick<IPrivateMenuItem, "hasAnyAuthorities" | 类型上不存在属性 'children' “身份证” | “到” | “图标”> & IOwnProps'.ts(2322)

我尝试了像const PrivateMenuItem: React.FC<IPrivateMenuItem>. 但是警告没有机会消失。除非我删除连接语句。由于 redux 的要求,这是不可能的。

然后,我将功能组件的 prop 类型切换为如下定义的IPrivateMenuItem。然后问题就没有了。我的问题是这是最佳做法还是有更简单的做法?

interface IPrivateMenuItem extends StateProps, IMenuItem, React.PropsWithChildren<IOwnProps> {}

没有导入的完整功能组件代码是

interface IOwnProps {
  hasAnyAuthorities?: string[];
}

interface IPrivateMenuItem extends StateProps, IMenuItem, 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);

标签: reactjstypescriptreact-reduxtslint

解决方案


没有看到整个组件有点困难,但如果它有帮助

连接的完整类型如下

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)

推荐阅读