【问题标题】:Nextjs: error when redirecting in HOC componentNextjs:在 HOC 组件中重定向时出错
【发布时间】:2021-10-03 07:57:45
【问题描述】:

我已经制作了这个 HOC 来重定向未经身份验证的用户:

export const ProtectRoute = ({ children }) => {
  const { isAuthenticated, isLoading } = useAuth();
  const router = useRouter()

  if (isLoading){
    return (<><Header/><h1>Loading</h1></>); 
  } 

  if (typeof window !== 'undefined') {
    if (!isAuthenticated && window.location.pathname !== '/emailLogin'){
      return router.push("/emailLogin")
    }
  }
  
  return children;
};

然后我用它包装了我的 _app.js 组件:

     <AuthProvider>
        <ProtectRoute>
          <SearchProvider>
            <Component {...pageProps} />
          </SearchProvider>
        </ProtectRoute>
      </AuthProvider>

重定向时出现以下错误:

react-dom.development.js?61bb:20085 The above error occurred in the <ProtectRoute> 
component:

at ProtectRoute (webpack-internal:///./contexts/auth.js:721:25)
at AuthProvider (webpack-internal:///./contexts/auth.js:49:23)
at ToastProvider (webpack-internal:///./node_modules/react-toast-notifications/dist/ToastProvider.js:61:5)
at MyApp (webpack-internal:///./pages/_app.js:57:24)
at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:26:47)
at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:86:23)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:160:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:648:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:784:25)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

关于为什么这不起作用的任何想法?

【问题讨论】:

标签: react-router next.js


【解决方案1】:

修复它。 这是因为我在 router.push("...")

上使用了 return

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2021-11-26
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多