React中用window.location.pathname隐藏头部注册页不生效如何解决
问题原因
你编写的路径判断逻辑存在语法错误,原有代码window.location.pathname === '/login' && '/register'的实际执行规则是:
- 仅当路径等于
/login时,整个表达式返回真值,触发三元运算的null分支隐藏头部 - 当路径等于
/register时,window.location.pathname === '/login'判断结果为假,整个表达式返回假值,触发三元运算的<Main />分支展示头部,这就是注册页逻辑不生效的原因。
修复方案
快速修复
直接修改判断逻辑即可,用数组匹配的写法更简洁,后续新增需要隐藏头部的路径也可以直接在数组中添加:
// 替换原有HideHeader定义逻辑即可 let HideHeader = ['/login', '/register'].includes(window.location.pathname) ? null : <Main />
更规范的React Router实现方案
不建议直接操作window.location获取路径,容易出现路由状态和组件渲染不同步的问题,推荐用React Router提供的useLocation Hook获取当前路径,需要调整部分代码结构:
- 首先导入
useLocation:
import { BrowserRouter as Router, Switch, Route, Link, useLocation // 新增导入 } from "react-router-dom";
- 调整组件结构,因为
useLocation必须在<Router>包裹的内部组件中调用:
// 抽离路由内部逻辑为子组件 function AppContent() { const location = useLocation() const HideHeader = ['/login', '/register'].includes(location.pathname) ? null : <Main /> return ( <> {HideHeader} <Switch> <Route path="/login"> <Login /> </Route> <Route exact path="/register"> <Register /> </Route> <Route exact path="/dashboard"> <Dashboard /> </Route> <Route exact path="/Clients"> <Clients /> </Route> <Route exact path="/addClient"> <AddClient /> </Route> <Route exact path="/Calendar"> <CalendarSection /> </Route> <Route exact path="/Clients/:id"> <EditClient /> </Route> <Route exact path="/Clients/:id/addDiet"> <AddDiet /> </Route> </Switch> </> ) } export default function MainApp() { return ( <Router> <AppContent /> </Router> ) }
内容的提问来源于stack exchange,提问作者Chen
相关产品推荐
相关产品推荐

