ReactJS:根据路由路径修改Loader的API请求URL
解决方案:根据路由路径动态修改API请求URL
步骤1:在Loader中获取当前路由信息
React Router的loader函数会接收request参数,通过该参数可解析出当前路由路径,以此判断要请求的API地址。
步骤2:修改EmpPage.js中的代码
调整loadEmpRequests函数,接收路由路径作为参数,根据不同路径生成对应API URL;同时修改loader函数,传递当前路由信息:
async function loadEmpRequests(pathname) { // 根据路由路径拼接不同的API地址 let url = "http://localhost:8000/empData"; if (pathname.includes("retired")) { url = "http://localhost:8000/empData/retired"; } else if (pathname.includes("resigned")) { url = "http://localhost:8000/empData/resigned"; } // 默认路由(index)使用原URL const response = await fetch(url, { method: "GET", }); const resData = await response.json(); return resData.data; } export function loader({ request }) { const url = new URL(request.url); // 获取当前路由的路径部分 const pathname = url.pathname; return defer({ empRequests: loadEmpRequests(pathname), }); }
步骤3:同步App.js中的loader引用
确保App.js里的empListLoader指向EmpPage导出的loader:
// 先导入EmpPage的loader import { loader as empListLoader } from './EmpPage'; // 路由配置部分保持不变 { path: "emp-detail", element: <EmpRootLayout />, children: [ { index: true, element: <EmpPage />, loader: empListLoader, }, { path: "retired", element: <EmpPage />, loader: empListLoader, }, { path: "resigned", element: <EmpPage />, loader: empListLoader, }, ], }
补充优化
如果API地址规则是路由路径对应接口后缀(比如/emp-detail/retired对应/empData/retired),可以用更灵活的方式提取路径片段,避免新增路由时修改判断逻辑:
// 提取emp-detail后的路径部分 const pathSegment = pathname.split('/emp-detail/')[1] || ''; let url = `http://localhost:8000/empData${pathSegment ? '/' + pathSegment : ''}`;
内容的提问来源于stack exchange,提问作者Silver Sky
相关产品推荐
相关产品推荐

