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

How to change the title on every page with a reusable navbar in React?

我正在开发一个带有可重用导航栏的 React 应用程序。我希望每次转到新页面时更改应用程序名称(在导航栏中)。

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

但是还不行。我得到错误:太多 re-renders。 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])