代码之家  ›  专栏  ›  技术社区  ›  Shawn Andrews

npm更新后反应无状态组件损坏

  •  2
  • Shawn Andrews  · 技术社区  · 8 年前

    interface INotFoundPageContainerProps {
        history: any;
    }
    
    class NotFoundPageContainer extends React.Component<INotFoundPageContainerProps, any> {
    
        constructor(props: INotFoundPageContainerProps) {
            super(props);
            this.onClickHomeButton = this.onClickHomeButton.bind(this);
        }
    
        onClickHomeButton(): void {
            this.props.history.push('/');
        }
    
        render() {
            return (
                <NotFoundPage
                    onClickHomeButton={this.onClickHomeButton}
                />
            );
        }
    
    }
    
    export default withRouter(NotFoundPageContainer);
    

    错误:

    TS2345: Argument of type 'typeof NotFoundPageContainer' is not assignable to parameter of type 'ComponentType<RouteComponentProps<any, StaticContext, any>>'.
      Type 'typeof NotFoundPageContainer' is not assignable to type 'StatelessComponent<RouteComponentProps<any, StaticContext, any>>'.
        Type 'typeof NotFoundPageContainer' provides no match for the signature '(props: RouteComponentProps<any, StaticContext, any> & { children?: ReactNode; }, context?: any): ReactElement<any>'.
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Lyubomir    8 年前

    React.Component的属性类型不正确,因为您正在用router HOC包装它。


    组成部分 <NotFoundPageContainer/> withRouter ,它传递特定于路由器的属性,但在 NotFoundPageContainer 的类型定义。

    考虑一下这样的事情吧

    import { RouteComponentProps } from 'react-router-dom';
    
    interface INotFoundPageContainerRouterProps {
        history: any;
    }
    
    interface INotFoundPageContainerProps 
      extends RouteComponentProps<INotFoundPageContainerRouterProps> {
    
    } 
    

    然后就可以正确地定义组件的类型了

    class NotFoundPageContainer 
      extends React.Component<INotFoundPageContainerProps, any> { ... }