javascript 如何将路径从APIMap到React Router?

pdkcd3nj  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(129)

我计划Map从API获得的路径。它将被设置到routeList中。然后我想Map到"/app"路由的一个子路由中。

const [routeList, setRouteList] = useState([]);
useEffect(() => {
  Promise.all([
    axios.get("http://localhost:5000/rights"),
    axios.get("http://localhost:5000/children")
  ])
    .then((res) => {
      setRouteList([...res[0].data, ...res[1].data]);
    });
}, []);
const element = useRoutes([
  {
    path: "/login",
    element: LazyLoad("login/Login"),
  },
  {
    path: "/app",
    element: <AuthComponent> 
   {LazyLoad("sandbox/Sandbox")}</AuthComponent>,
      children: [
        {
          path: "",
          element: <Redirect to="/app/home" />,
        },
        routeList.map((item) => {
          `path: ${item.key}, element: 
${LocalRouterMapping[item.key]}`;
        }),
        {
          path: "*",
          element: 
    LazyLoad("noPermission/NoPermission"),
          },
        ],
     },
    ]);

但执行此操作时会出现错误

routeList.map((item) => {
  `path: ${item.key}, element: ${LocalRouterMapping[item.key]}`;
}),

命令提示符中的错误为Line 40:11: Expected an assignment or function call and instead saw an expression no-unused-expressions
我试图改变格式,但仍然不起作用。
我有另一个问题,我的元素需要 Package 在LazyLoad函数中才能使用React.Suspence。我可以知道如何才能做到这一点吗?

const LazyLoad = (path) => {
const Comp = React.lazy(() => 
  import(`../views/${path}`));
  return (
    <React.Suspense fallback={<>Loading...</>}>
      <Comp />
    </React.Suspense>
  );
};

我是这样做的,但是没有创建包含元素的路径,我只会一直重定向到路径:“*”

routeList.map((item) => ({
      path: item.key,
      element: LazyLoad(`${LocalRouterMapping[item.key]}`),
    })),

这是我的LocalRouterMapping

const LocalRouterMapping = {
  "/home": "dashboard/Dashboard",
  "/user-manage/list": "user-manage/UserList",
  "/access-manage/access/list": "access-manage/AccessList",
  "/access-manage/role/list": "access-manage/RoleList",
  "/news-manage/add": "inventory/CreateInventory",
  "/news-manage/draft": "inventory/InventoryDraft",
  "/news-manage/category": "inventory/InventoryCategory",
  "/audit-manage/audit": "audit/AuditInventory",
  "/audit-manage/list": "audit/AuditList",
};

这些数据来自axios

这是我的全部代码

import React, { useEffect, useState } from "react";
import { useRoutes } from "react-router-dom";
import Redirect from "../components/Redirect";
import axios from "axios";

const LocalRouterMapping = {
"/home": "dashboard/Dashboard",
"/user-manage/list": "user-manage/UserList",
"/access-manage/access/list": "access-manage/AccessList",
"/access-manage/role/list": "access-manage/RoleList",
"/news-manage/add": "inventory/CreateInventory",
"/news-manage/draft": "inventory/InventoryDraft",
"/news-manage/category": "inventory/InventoryCategory",
"/audit-manage/audit": "audit/AuditInventory",
"/audit-manage/list": "audit/AuditList",};
export default function IndexRouter() {
  const [routeList, setRouteList] = useState([]);
  useEffect(() => {Promise.all([axios.get("http://localhost:5000/rights"), axios.get("http://localhost:5000/children")]).then((res) => {
  const combinedRoutes = [...res[0].data, ...res[1].data];
  setRouteList(combinedRoutes.filter((item) => LocalRouterMapping[item.key]));
});
}, []);
const element = useRoutes([
  {
    path: "/login",
    element: LazyLoad("login/Login"),
  },
  {
    path: "/app",
    element: <AuthComponent> {LazyLoad("sandbox/Sandbox")} </AuthComponent>,
   children: [
    {
      path: "",
      element: <Redirect to="/app/home" />,
    },
    routeList.map((item) => ({
      path: item.key.slice(1),
      element: <AuthComponent>{LazyLoad(LocalRouterMapping[item.key])}</AuthComponent>,
    })),
    {
      path: "*",
      element: LazyLoad("noPermission/NoPermission"),
    },
  ],
},
{
  path: "/dashboard",
  element: <AuthComponent>{LazyLoad("dashboard/Dashboard")}</AuthComponent>,
},
{
  path: "/product",
  element: <AuthComponent> 
 {LazyLoad("dashboard/Dashboard")} 
 </AuthComponent>,
      },
    {
      path: "/",
      element: <Redirect to="/app" />,
    },
    {
      path: "*",
      element: LazyLoad("notFound/NotFound"),
    },
  ]);
  return element;
}

function AuthComponent({ children }) {
const isLogin = localStorage.getItem("token");
return isLogin ? children : <Redirect to="/login" />;
}

const LazyLoad = (path) => {
const Comp = React.lazy(() => import(`../views/${path}`));
return (
  <React.Suspense fallback={<>Loading...</>}>
    <Comp />
  </React.Suspense>
);
};
6tr1vspr

6tr1vspr1#

您正在使用字符串模板Map到字符串值,但也无法返回Map值。您应该改为Map到RouteObject对象。
示例:

routeList.map(({ key }) => ({
  path: key,
  element: LazyLoad(LocalRouterMapping[key]),
})),

完整代码:

const element = useRoutes([
  {
    path: "/login",
    element: LazyLoad("login/Login"),
  },
  {
    path: "/app",
    element: <AuthComponent>{LazyLoad("sandbox/Sandbox")}</AuthComponent>,
    children: [
      {
        index: true,
        element: <Redirect to="/app/home" />,
      },
      routeList
        // Ensure there is component mapping
        .filter(item => LocalRouterMapping[item.key])
        // Map to RouteObject properties
        .map((item) => ({
          path: item.key,
          element: LazyLoad(LocalRouterMapping[item.key]),
        })),
      {
        path: "*",
        element: LazyLoad("noPermission/NoPermission"),
      },
    ],
  },
]);
6uxekuva

6uxekuva2#

我通过使用Route组件而不是useRoute找到了解决方案。
下面是使用相同Map样式的源代码。

const LocalRouterMapping = {
  "/home": "dashboard/Dashboard",
  "/user-manage/list": "user-manage/UserList",
  "/access-manage/access/list": "access-manage/AccessList",
  "/access-manage/role/list": "access-manage/RoleList",
  "/inventory-manage/add": "inventory/CreateInventory",
  "/inventory-manage/list": "inventory/InventoryList",
  "/inventory-manage/preview/:id": "inventory/InventoryDetails",
  "/inventory-manage/update/:id": "inventory/InventoryUpdate",
  "/inventory-manage/category": "inventory/InventoryCategory",
};

<Routes>
  <Route path="/login" element={LazyLoad("login/Login")} />
  <Route path="/app" element={LazyLoad("sandbox/Sandbox")}>
    <Route path="" element={<Navigate to={"home"} />} />
    <Route path="*" element={<AuthComponent>{LazyLoad("noPermission/NoPermission")}</AuthComponent>} />
    {routeList.map((item) => {
      if (checkPagePermission(item) && checkUserPermission(item)) {
        return (
          <Route
            path={item.key.slice(1)}
            key={item.key.slice(1)}
            element={<AuthComponent>{LazyLoad(LocalRouterMapping[item.key])}</AuthComponent>}
          />
        );
      }
      return <Route path="*" key={item.key.slice(1)} element={<AuthComponent>{LazyLoad("noPermission/NoPermission")}</AuthComponent>} />;
    })}
  </Route>
  <Route path="/" element={<Navigate to={"/app"} />} />
  <Route path="*" element={LazyLoad("notFound/NotFound")} />
</Routes>

相关问题