You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目如何实现移动端用户自动跳转至mobile站点并支持本地测试

移动端访问重定向实现方案

首先实现移动端UA识别逻辑,新增工具函数/src/utils/userAgent.js:

export const isMobile = () => {
  const ua = navigator.userAgent.toLowerCase();
  return /(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i.test(ua);
}

在根组件挂载阶段执行跳转判断,避免死循环(已在移动端域名、本地开发环境默认不触发自动跳转):

// App.js
import { useEffect } from 'react';
import { isMobile } from './utils/userAgent';
import DesktopRoutes from './routes/desktopRoutes';
import MobileRoutes from './routes/mobileRoutes';

function App() {
  useEffect(() => {
    const currentHost = window.location.host;
    if (
      isMobile() 
      && !currentHost.startsWith('mobile.') 
      && process.env.NODE_ENV !== 'development'
    ) {
      // 跳转时保留当前路径和查询参数
      window.location.href = `https://mobile.${currentHost}${window.location.pathname}${window.location.search}`;
    }
  }, []);

  // 本地开发环境直接根据UA渲染对应端路由,无需跳转
  return isMobile() ? <MobileRoutes /> : <DesktopRoutes />;
}
本地localhost测试方法

修改本地hosts文件模拟线上域名环境:

  • Windows系统路径:C:\Windows\System32\drivers\etc\hosts
  • Mac/Linux系统路径:/etc/hosts
    在hosts文件末尾追加两行配置:
127.0.0.1 example.test
127.0.0.1 mobile.example.test

启动项目时指定HOST:

# React CRA 项目启动命令
HOST=example.test npm start

测试时打开Chrome开发者工具,切换移动端模拟模式,访问example.test:3000即可验证跳转逻辑,需要测试移动端路由直接访问mobile.example.test:3000即可。

适配多端的React项目文件结构参考
/src
  /components
    /common // 两端通用组件,比如按钮、弹窗、通用工具组件
    /desktop // 桌面端专属组件
    /mobile // 移动端专属组件
  /pages
    /desktop // 桌面端页面组件
    /mobile // 移动端页面组件
  /routes
    desktopRoutes.js // 桌面端路由表配置
    mobileRoutes.js // 移动端路由表配置
  /utils
    userAgent.js // UA判断工具函数
  App.js // 根组件
  index.js // 项目入口
react-router-dom baseUrl配置方案

如果移动端站点部署在子路径(比如example.com/m),可以通过BrowserRouter的basename属性配置baseUrl:

// 移动端路由入口
import { BrowserRouter } from 'react-router-dom';
import MobileRoutes from './mobileRoutes';

const MobileApp = () => {
  // 也可以通过环境变量动态配置不同端的basename
  return (
    <BrowserRouter basename={process.env.REACT_APP_MOBILE_BASE || '/m'}>
      <MobileRoutes />
    </BrowserRouter>
  )
}

如果是独立子域名部署(mobile.example.com),不需要额外配置basename,直接加载对应端的路由表即可。

内容的提问来源于stack exchange,提问作者CryptoGeek981

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:54:07