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

React项目如何实现deeplink,登录后自动跳转至原目标页面

实现方案

你现在的PrivateRoute已经自动存储了用户未登录时的目标访问地址,只需要做两处修改即可完成需求:

1. 补充客户详情页路由

你当前的路由配置中缺少/customer-profile/:id的匹配规则,先在嵌套的内部Switch中添加对应的私有路由:

<Route path="/">
  <SideBar />
  <Switch>
    {/* 新增客户详情页路由,CustomerProfile为你对应的页面组件 */}
    <PrivateRoute path="/customer-profile/:userId">
      <CustomerProfile />
    </PrivateRoute>
    <PrivateRoute path="/tier-list">
      <TierList />
    </PrivateRoute>
    <PrivateRoute path="/privacy-policy">
      <PrivacyPolicy />
    </PrivateRoute>
    <PrivateRoute path="/help">
      <Help />
    </PrivateRoute>
  </Switch>
</Route>

2. 修改登录组件的成功跳转逻辑

在Login组件中读取PrivateRoute存在路由状态里的目标地址,登录成功后优先跳转该地址,无目标地址时再跳转首页:

import { useHistory, useLocation } from 'react-router-dom';

function Login() {
  const history = useHistory();
  const location = useLocation();

  // 你的登录提交逻辑
  const handleLogin = async (loginForm) => {
    // 调用登录接口、存储用户信息逻辑省略
    const loginRes = await api.login(loginForm);
    if (loginRes.success) {
      // 优先跳转之前要访问的地址,默认跳首页,兼容带查询参数的场景
      const targetPath = location.state?.from 
        ? `${location.state.from.pathname}${location.state.from.search || ''}` 
        : '/';
      history.push(targetPath);
    }
  }

  // 其余组件逻辑省略
}

如果你的客户详情页需要读取路径中的用户ID,可以在组件内用useParams获取:

import { useParams } from 'react-router-dom';

function CustomerProfile() {
  const { userId } = useParams();
  // 后续用userId拉取对应客户信息即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:15:09