代码之家  ›  专栏  ›  技术社区  ›  user1283776

为什么在将主题包装组件传递到路由时发出警告?

  •  0
  • user1283776  · 技术社区  · 5 年前

    我得到以下警告使用 "react-router": "4.3.1" "styled-components": "4.1.3"

    index.js:2178 Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`.
        in Route (created by Routes)
        in Routes (created by Route)
        in Route (created by withRouter(Routes))
        in withRouter(Routes) (created by App)
        in div (created by App)
        in App (created by Route)
        in Route (created by withRouter(App))
        in withRouter(App) (created by StartPage)
        in div (created by ScrollToTop)
        in ScrollToTop (created by Route)
        in Route (created by withRouter(ScrollToTop))
        in withRouter(ScrollToTop) (created by StartPage)
        in ThemeProvider (created by StartPage)
        in Router (created by ConnectedRouter)
        in ConnectedRouter (created by StartPage)
        in Provider (created by StartPage)
        in StartPage
    

    这是我的 Routes

    interface RoutesProps extends RouteComponentProps<{}> {
    }
    
    class Routes extends React.Component<RoutesProps, {}> {
        public render() {
            return (
                <Switch>
                    <Route path="/otii/standard" component={OtiiStandard} />
                </Switch>
            );
        }
    }
    export default withRouter(Routes);
    

    import * as React from 'react';
    import styled, { withTheme } from 'styled-components';
    
    interface OtiiStandardProps {
        // tslint:disable-next-line:no-any
        theme: any;
    }
    
    const ImageContainer = styled.div`
        max-width: 150px;
        margin-bottom: 15px;
    `;
    
    const Center = styled.div`
        text-align: center;
    `;
    
    const SectionContainer2 = styled(SectionContainer)`
        margin-top: 38px;
    `;
    
    // tslint:disable:max-line-length
    
    const OtiiStandard = (props: OtiiStandardProps) => {
        return (
            <>
                <Center>
                    ....
                </Center>
            </>
        );
    };
    
    export default withTheme(OtiiStandard);
    

    我可以通过两种不同的方式得到警告:

    将路线更改为:

    <Route path="/otii/standard" component={() => <OtiiStandard/>} />
    

    (二)

    不要用主题包装otisistandard

    export default OtiiStandard;
    

    • 为什么会出现这个警告?我还有许多其他的组件,我也用同样的方法编写,它们也被 withTheme 不会引起警告的?
    • <Route path="/otii/standard" component={() => <OtiiStandard/>} /> 或者我的代码看起来有什么问题吗?
    0 回复  |  直到 5 年前