reactrouter 有没有办法实现动态路由?

作者站长头像
站长
· 阅读数 7

想实现先请求接口然后再生成路由改如何做到?(下面代码试了几次都不行)

import { useState, useEffect } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { Button } from 'antd-mobile'
import axios from 'axios'
import {
    createBrowserRouter,
    RouterProvider,
} from "react-router-dom";
import {Router as RemixRouter} from "@remix-run/router/dist/router";

 function test_request() {
    return axios.get('http://localhost:8888/api/')
        .then(function (response) {
            return response.data.Response
        })
}
interface Route { path: string, element?: string }

function App() {
  const [route, setRoute] = useState<RemixRouter>()
    // createBrowserRouter
    const router = test_request().then((data) => {
        // let c = data.map((v : Route) => {
        //     return { path: v.path, element: <div>2222222222222</div> }
        // })
        // setRoute(createBrowserRouter(c))
        return createBrowserRouter(data)
    })

    // useEffect(() => {
    //     test_request().then((data) => {
    //         let c = data.map((v : Route) => {
    //             return { path: v.path, element: <div>2222222222222</div> }
    //         })
    //         // setRoute(createBrowserRouter(c))
    //         return c
    //     })
    //
    //
    // },[])

  return (
    <div className="App">
      <div>
          <img src={viteLogo} className="logo" alt="Vite logo" />
      </div>
        <RouterProvider router={router} />
    </div>
  )
}

export default App
回复
1个回答
avatar
test
2024-07-03
import { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import axios from 'axios';

function App() {
  const [routes, setRoutes] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:8888/api/')
      .then(response => {
        const routes = response.data.Response.map(route => ({
          path: route.path,
          component: () => <div>{route.element}</div>,
        }));
        setRoutes(routes);
      });
  }, []);

  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <Route key={index} path={route.path} component={route.component} />
        ))}
      </Switch>
    </Router>
  );
}

export default App;
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容