React Ts 尝试创建受保护的路由,但出现错误。

huangapple go评论54阅读模式
英文:

React Ts trying to create guarded routed but getting an error

问题

抱歉,你提供的内容中包含了代码部分,但你要求我不要翻译代码。以下是你要求翻译的非代码部分:

Hi I tried creating guards for my routes but I am getting this error:

[Error] Error: [GuardedRoute] is not a component. All component children of must be a or <React.Fragment>

This is my code:

GuardedRoute.tsx-

import { Route, Navigate } from 'react-router-dom';
import { useUserInfo } from '../context/UserContext';

export const GuardedRoute = ({ path, element: Element, ...rest }: any) => {
  const { userInfo } = useUserInfo();

  if (userInfo.id !== '') {
    return <Route path={path} element={Element} {...rest} />;
  } else {
    return <Navigate to="/" replace />;
  }
};

App.tsx

<BrowserRouter>
  <Nav></Nav>
  <div className="w-[100vw] fixed top-[50px] z-[100] flex flex-col">
    {
      ErrorMessages.map((message, index) => (
        <div className="w-[300px] h-[50px] mt-[10px] mx-auto bg-red-600/90 rounded-md grid place-content-center" key={index}>
          <p className="font-bold text-gray-200 text-center">{message}</p>
        </div>
      ))
    }
  </div>
  <Routes>
    <Route path="/" element={<Home />} />
    <GuardedRoute path="/profile/:select?" element={<Profile />} />
    <GuardedRoute path="/checkout" element={<CheckOut />} />
    <Route path="/register" element={<Register />} />
    <Route path="/login" element={<Login />} />
    <Route path="/browse" element={<Browse />} />
    <Route path="/product/:id" element={<Product />} />
    <Route path="/404" element={<PageNotFound />} />
    <Route path="*" element={<Navigate to="/404" />} />
  </Routes>
</BrowserRouter>

Does anyone have a solution for this error? thanks.

英文:

Hi I tried creating guards for my routes but I am getting this error:

[Error] Error: [GuardedRoute] is not a &lt;Route&gt; component. All component children of &lt;Routes&gt; must be a &lt;Route&gt; or &lt;React.Fragment&gt;

This is my code:

GuardedRoute.tsx-

import { Route, Navigate } from &#39;react-router-dom&#39;;
import { useUserInfo } from &#39;../context/UserContext&#39;;

export const GuardedRoute = ({ path, element: Element, ...rest }: any) =&gt; {
  const { userInfo } = useUserInfo();

  if (userInfo.id !== &#39;&#39;) {
    return &lt;Route path={path} element={Element} {...rest} /&gt;;
  } else {
    return &lt;Navigate to=&quot;/&quot; replace /&gt;;
  }
};

App.tsx

 &lt;BrowserRouter&gt;
                &lt;Nav&gt;&lt;/Nav&gt;
                &lt;div className=&quot;w-[100vw] fixed top-[50px] z-[100] flex flex-col&quot;&gt;
                {
                  ErrorMessages.map((message,index)=&gt;(
                      &lt;div className=&quot;w-[300px] h-[50px] mt-[10px] mx-auto bg-red-600/90 rounded-md grid place-content-center&quot; key={index}&gt;
                        &lt;p className=&quot;font-bold text-gray-200 text-center&quot;&gt;{message}&lt;/p&gt;
                      &lt;/div&gt;
                  ))
                }
                &lt;/div&gt;
                  &lt;Routes&gt;
                    &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;
                    &lt;GuardedRoute path=&quot;/profile/:select?&quot; element={&lt;Profile /&gt;} /&gt;
                    &lt;GuardedRoute path=&quot;/checkout&quot; element={&lt;CheckOut /&gt;}/&gt;
                    &lt;Route path=&quot;/register&quot; element={&lt;Register /&gt;} /&gt;
                    &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;
                    &lt;Route path=&quot;/browse&quot; element={&lt;Browse /&gt;} /&gt;
                    &lt;Route path=&quot;/product/:id&quot; element={&lt;Product /&gt;} /&gt;
                    &lt;Route path=&quot;/404&quot;  element={&lt;PageNotFound /&gt;}/&gt;
                    &lt;Route path=&quot;*&quot;  element={&lt;Navigate to=&quot;/404&quot; /&gt;}/&gt;
                  &lt;/Routes&gt;
                &lt;/BrowserRouter&gt;

Does anyone have a solution for this error? thanks.

答案1

得分: 1

最好将所有私有路由放在 Authguard 中,而不是为每个组件提供 Authguard。您可以自定义身份验证,例如,如果特定用户存在 cookie,则身份验证为 true,否则为 false。

import { Outlet, Navigate } from 'react-router-dom';

const Authguard = () => {

    let auth = false;
    return (
        auth ? <Outlet/> : <Navigate to="/" />
    )
}

export default Authguard

现在,您的路由将如下所示,例如在 App.tsx 中:

function App(){
    return(
        <Routes>
            <Route path="/" element={<Login />} />
        
            <Route element={<Authguard />}> 
                <Route path="/register" element={<Register />} />
                <Route path="/home" element={<Home />} />
            </Route>
        </Routes>
    )
}

这显示您的注册和主页组件是私有的而登录组件是公共的
英文:

It is better to put all the private routes inside Authguard instead of providing Authguard to each component. you can customize the auth, like if there is cookie exists of particular user, then auth is true, otherwise false.

import { Outlet, Navigate } from &#39;react-router-dom&#39;;

const Authguard = () =&gt; {

    let auth = false;
    return(
        auth ? &lt;Outlet/&gt; : &lt;Navigate to=&quot;/&quot;/&gt;
    )
}

export default Authguard

Now you Routes will be like, e.g in App.tsx

  function App(){
    return(
     &lt;Routes&gt;
          &lt;Route path=&quot;/&quot; element={&lt;Login /&gt;} /&gt;
    
           &lt;Route element={&lt;Authguard /&gt;}&gt; 
               &lt;Route path=&quot;/register&quot; element={&lt;Register /&gt;} /&gt;
               &lt;Route path=&quot;/home&quot; element={&lt;Home /&gt;} /&gt;
          &lt;/Route&gt;
     &lt;/Routes&gt;)
    }

This shows your Register and Home components are private, and Login component is public.

huangapple
  • 本文由 发表于 2023年6月2日 01:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定