如何在React中使用可重用的导航栏更改每个页面的标题?



我正在开发一个具有可重用导航条的React应用程序。我希望应用程序的名称(在导航栏)改变,每次我进入一个新的页面。

我试图用window.location.pathname获取路径名,然后我想用useState为每个路径名设置一个不同的标题,我传递给导航栏。

但它还不起作用。我得到错误:太多的重新渲染。React会限制渲染的次数,以防止无限循环。

有人能帮我一下吗?in App.js

const [titleApp, setTitleApp] = useState("Home");
switch (window.location.pathname) {
case "/":
setTitleApp("Home");
break;
case "/worklist":
setTitleApp("Worklist");
break;
case "/analytics":
setTitleApp("analytics");
break;
default:
setTitleApp("Home");
break;
}
return (
<div className="GlobalDiv">
<Router>

<NavBar
title={titleApp}
/>
<div className="MainDiv">
<Switch>
<Route exact path="/" component={Springboard} />
<Route exact path="/worklist" component={Worklist} />
<Route path="/analytics" component={AnalyticsDashboard} />
</Switch>
</div>
</Router>
</div>
);
}
export default App; ```

你可以看看这是否有效,

useEffect(() => {
switch (window.location.pathname) {
case "/":
setTitleApp("Home");
break;
case "/worklist":
setTitleApp("Worklist");
break;
case "/analytics":
setTitleApp("analytics");
break;
default:
setTitleApp("Home");
break;
}
}, [window.location.pathname]);

你可以让它和历史监听器一起工作

https://reactrouter.com/web/api/Hooks/uselocation

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

const location = useLocation()

React.useEffect(() => {
switch (location.pathname) {
case "/":
setTitleApp("Home");
break;
case "/worklist":
setTitleApp("Worklist");
break;
case "/analytics":
setTitleApp("analytics");
break;
default:
setTitleApp("Home");
break;
}
}, [location, setTitleApp])

import { useHistory } from 'react-router-dom'
const { listen } = useHistory()
React.useEffect(() => {
const unlisten = listen((location) => {
switch (location.pathname) {
case "/":
setTitleApp("Home");
break;
case "/worklist":
setTitleApp("Worklist");
break;
case "/analytics":
setTitleApp("analytics");
break;
default:
setTitleApp("Home");
break;
}
})
return unlisten
}, [listen, setTitleApp])

相关内容

  • 没有找到相关文章

最新更新