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

React Router V6 刷新后如何保持当前路由(Shopify+Ngrok场景)

解决Shopify React应用Ngrok刷新跳回根路由的问题

问题根源

  • Shopify AppBridge的forceRedirect: true配置会在页面加载时强制重定向到根路径
  • 单页应用(SPA)部署在Ngrok时,服务器未配置路由 fallback,刷新非根路径时服务器找不到对应资源,触发重定向回根路由

解决方案

1. 修改AppBridgeProvider的强制重定向配置

把forceRedirect设为false,避免AppBridge自动强制跳转到根路由:

<AppBridgeProvider
  config={{
    apiKey: process.env.SHOPIFY_API_KEY,
    host: new URL(location.href).searchParams.get("host"),
    forceRedirect: false, // 关闭强制重定向
  }}
>

2. 配置Vite开发服务器的路由 fallback

在vite.config.js中添加服务器 fallback 配置,让所有路由请求都返回index.html,确保React Router能正确处理刷新后的路由:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    fallback: 'index.html', // 所有路由返回index.html
  },
});

3. 生产环境服务器配置(构建后部署)

如果是部署构建好的生产版本,需要在Node.js服务器(比如Express)中配置所有路由返回index.html,示例代码:

const express = require('express');
const path = require('path');
const app = express();

// 托管静态资源
app.use(express.static(path.join(__dirname, 'dist')));

// 所有路由请求返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3000);

4. 移除自定义的localStorage路由逻辑

之前用localStorage结合useLocation()/useNavigate()实现的路由逻辑会干扰React Router的原生历史记录管理,导致无法回退页面,直接删除这部分代码即可,React Router会自动处理刷新后的路由匹配。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:10:40