【发布时间】:2021-01-15 17:38:14
【问题描述】:
我想在用户登录时显示navbar
当用户按下登录按钮时,我将页面替换为主页
我尝试定义使用状态,如果路径名不等于 /login 或 /step-two 将其设置为 true 然后在应用程序中我说如果 usestate 等于 true 则显示导航栏
但我在刷新页面之前看不到导航栏
这是我在useeffect中尝试过的
const [hasNavBar, setNavBar] = useState(false)
useEffect(() => {
console.log(history.location.pathname);
if (history.location.pathname !== '/login'|| history.location.pathname !=='/step-two'
) {
setNavBar(true)
}
}, [])
这是完整的代码
const App = () => {
const [hasNavBar, setNavBar] = useState(false)
useEffect(() => {
console.log(history.location.pathname);
if (history.location.pathname !== '/login' ||
history.location.pathname !== '/step-two'
) {
setNavBar(true)
}
}, [])
return (
<div>
<SNackbar></SNackbar>
<Router history={history}>
<div>
<Route path="/login" exact component={FirstLogin} />
<Route path="/step-two" exact component={SecondLogin} />
<Route path="/home" exact component={Home} />
<Route path='/ranking-list' exact component={RankingListPage} />
</div>
</Router>
<div>
{hasNavBar ?
<div>
<BottomNavBar />
</div> : ''
}
</div>
</div>
)
};
export default App;
更新
我尝试使用 history.listen bu 仍然看到相同的错误const App = () => {
const [hasNavBar,setnavbar]=useState(false)
useEffect(() => {
history.listen(()=>{
if (history.location.pathname === '/'||history.location.pathname === '/steptwo') {
setnavbar(false);
}else{setnavbar(true);}
})
if (localStorage.getItem("token") && history.location.pathname === '/') {
history.replace('/home');
}
}, [])
return (
<div>
<SNackbar></SNackbar>
<Router history={history}>
<div>
<Route path="/" exact component={FirstLogin} />
<Route path="/steptwo" exact component={SecondLogin} />
<Route path="/home" exact component={Home} />
<Route path='/ranking-list' exact component={RankingListPage} />
</div>
</Router>
{hasnavbar?
<div
style={{ position: 'fixed', bottom: '0px', width: "100%", height: '80px' }}>
<BottomNavBar />
</div>:''
}
</div>
)
};
export default App;
【问题讨论】:
-
尝试将
{hasnavbar?替换为{hasNavBar?,因为它与您的使用状态不同
标签: javascript reactjs routes react-router