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

如何根据前置路由打开React页面时激活指定标签页?

问题描述

我有一个包含三个标签页(“Instrucciones”“Normativa”“Wiki”)的React页面,代码如下:

import React, { useState, useEffect } from 'react';
import { Navbar } from '../components';

function Information() {
  const [selectedTab, setSelectedTab] = useState('instrucciones');

  return (
    <>
      <Navbar>Información y normativa</Navbar>
      <div className="relative pt-16 pb-16 min-h-screen w-screen bg-gray-200">
        <div className="w-full overflow-visible ">
          <div className="flex overflow-x-scroll no-scrollbar max-w-full mt-4 ml-4 whitespace-nowrap">
            <button
              onClick={() => setSelectedTab('instrucciones')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'instrucciones' ? 'bg-primary font-bold active' : 'hover:border-stone-400'} mr-4`}
            >
              Instrucciones
            </button>
            <button
              onClick={() => setSelectedTab('normativa')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'normativa' ? 'bg-primary font-bold active' : 'hover:border-stone-400'} mr-4`}
            >
              Normativa
            </button>
            <button
              onClick={() => setSelectedTab('wiki')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'wiki' ? 'bg-primary font-bold active' : 'hover:border-stone-400'}`}
            >
              Wiki
            </button>
          </div>
          {selectedTab === 'instrucciones' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                INSTRUCTIONS
              </h1>
              
            </div>
          )}
          {selectedTab === 'normativa' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                NORMATIVA
              </h1>
              
            </div>
          )}
          {selectedTab === 'wiki' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                WIKI
              </h1>
              
            </div>
          )}
        </div>
      </div>
    </>
  );
}

export default Information;

需求:用户从/wiki路由进入该页面时自动激活Wiki标签页,从其他路由进入时默认激活Instrucciones标签页。我尝试使用useLocation但获取到空值,请问该如何实现?

解决方案

1. 确保组件处于Router上下文内

useLocation必须在React Router的上下文环境中才能正常工作,如果你的Information组件没有被BrowserRouter(或其他Router组件)包裹,就会出现获取空值的情况。先在根组件(比如App.js)中配置Router:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Information from './path/to/Information';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Information />} />
        <Route path="/wiki" element={<Information />} />
        {/* 其他路由配置 */}
      </Routes>
    </Router>
  );
}

2. 修改Information组件逻辑

引入useLocation并结合useEffect监听路由变化,自动设置激活的标签页:

import React, { useState, useEffect } from 'react';
import { Navbar } from '../components';
import { useLocation } from 'react-router-dom'; // 引入useLocation

function Information() {
  const [selectedTab, setSelectedTab] = useState('instrucciones');
  const location = useLocation();

  useEffect(() => {
    // 根据当前路由设置激活标签
    if (location.pathname === '/wiki') {
      setSelectedTab('wiki');
    } else {
      setSelectedTab('instrucciones');
    }
  }, [location.pathname]); // 依赖路由路径变化,路由切换时重新执行

  return (
    <>
      <Navbar>Información y normativa</Navbar>
      <div className="relative pt-16 pb-16 min-h-screen w-screen bg-gray-200">
        <div className="w-full overflow-visible ">
          <div className="flex overflow-x-scroll no-scrollbar max-w-full mt-4 ml-4 whitespace-nowrap">
            <button
              onClick={() => setSelectedTab('instrucciones')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'instrucciones' ? 'bg-primary font-bold active' : 'hover:border-stone-400'} mr-4`}
            >
              Instrucciones
            </button>
            <button
              onClick={() => setSelectedTab('normativa')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'normativa' ? 'bg-primary font-bold active' : 'hover:border-stone-400'} mr-4`}
            >
              Normativa
            </button>
            <button
              onClick={() => setSelectedTab('wiki')}
              className={`flex-1 py-2 px-4 text-center text-black bg-white rounded-full ${selectedTab === 'wiki' ? 'bg-primary font-bold active' : 'hover:border-stone-400'}`}
            >
              Wiki
            </button>
          </div>
          {selectedTab === 'instrucciones' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                INSTRUCTIONS
              </h1>
              
            </div>
          )}
          {selectedTab === 'normativa' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                NORMATIVA
              </h1>
              
            </div>
          )}
          {selectedTab === 'wiki' && (
            <div>
              <h1 className="mt-6 ml-3 p-3 text-left text-lg font-bold text-black">
                WIKI
              </h1>
              
            </div>
          )}
        </div>
      </div>
    </>
  );
}

export default Information;

关键说明

  • 组件必须在Router上下文内,这是useLocation能正常工作的前提,也是你之前获取空值的核心原因。
  • 通过useEffect监听location.pathname的变化,路由切换时自动更新选中的标签页,同时保留用户手动切换标签的交互逻辑。
  • 初始状态仍设为instrucciones,组件挂载时会根据当前路由自动覆盖这个值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:46:06