【问题标题】:React & Redux tslint WarningReact & Redux tslint 警告
【发布时间】:2021-05-20 13:53:39
【问题描述】:

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

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

类型'{孩子:字符串;图标:“用户”;到:字符串; }' 不可分配给类型 'IntrinsicAttributes & Pick & IOwnProps'。 类型 'IntrinsicAttributes & Pick & 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);

【问题讨论】:

    标签: reactjs typescript react-redux tslint


    【解决方案1】:

    看不到整个组件有点困难,但如果有帮助的话

    连接的完整类型如下

    connect&lt;TheMapStateToPropsType, TheDispatchToPropsType, TheComponentPropsType, TheStorePropsType&gt;

    你可以像这样输入你的组件:(我是用一个类来做的,但是你得到了一个功能组件的精神)

    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)
    

    【讨论】:

    • 谢谢,我添加了我的修复方法。另外,与基于类的组件定义相比,它有点不同。因为问题在于要包含 ReactComponent 的默认道具类型。
    猜你喜欢
    • 2017-08-24
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2017-10-24
    • 2017-12-20
    • 2019-04-17
    相关资源
    最近更新 更多