【问题标题】:Class constructor cannot be invoked without 'new' when returning <Component />返回 <Component /> 时,如果没有“new”,则无法调用类构造函数
【发布时间】:2021-06-29 02:45:18
【问题描述】:

我有下面的代码

   <ProtectedRoute path='/u/MyDashboard' component={DashboardPage} />

看起来像这样

export default function ProtectedRoute(props) {

    var [state, statesetter] = useState({ isAuthenticated:false });
    var [dataloaded, loadingsetter] = useState(false);
    useEffect(() => {
       
        statesetter({ isAuthenticated: true });
        loadingsetter(true);
    }, []);

    return (
        dataloaded == true ?
            <Route
                
                render={boo => (
                    state["isAuthenticated"] == true ?
                        <Component  { ...props } /> :
                        <Redirect to={'/login'} />

            )}
            /> :
            <LoadingSpinner></LoadingSpinner>

    )}

当它返回 &lt;component {...props}/&gt; 时,我收到以下错误:Class constructor DashboardPage cannot be invoked without 'new'。如何在组件标签中新建类,或者我们如何解决这个问题?

【问题讨论】:

    标签: reactjs react-router react-hooks


    【解决方案1】:

    我认为您缺少将 component 属性转换为 Component 以进行渲染。解构 props 对象并重命名component,然后传播其余部分。

    export default function ProtectedRoute({ component: Component, ...props }) {
      const [state, statesetter] = useState({ isAuthenticated: false });
      const [dataloaded, loadingsetter] = useState(false);
    
      useEffect(() => {
        statesetter({ isAuthenticated: true });
        loadingsetter(true);
      }, []);
    
      return dataloaded ? (
        <Route
          render={(routeProps) =>
            state.isAuthenticated ? (
              <Component {...props} {...routeProps} />
            ) : (
              <Redirect to={"/login"} />
            )
          }
        />
      ) : (
        <LoadingSpinner></LoadingSpinner>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 2021-12-23
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2017-09-29
      • 2018-09-19
      • 1970-01-01
      相关资源
      最近更新 更多