如何在 React js Web 应用程序中的页面导航上更改 Material UI ToolBar 中的标题?

Mir*_*hah 1 reactjs material-ui react-redux react-context

我有反应功能组件MainToolBar。在导航到其他页面(功能组件)时,我需要更改 MainToolBar 的标题。我怎么能这么做呢?使用 Context API 或 Redux 或任何其他简单的东西

以下是 MainToolBar.Js 的代码

 export default function MainToolBar() {
 const classes = useStyles();
      return (
        <div className={classes.root}>
          <AppBar position="static">
             <Toolbar>
               <Typography align="center" variant="h6" className ={classes.title}>
                ERP System
               </Typography>
               <Button color="inherit">Login</Button>
             </Toolbar>
          </AppBar>
        </div>
      );
    }
Run Code Online (Sandbox Code Playgroud)

以下是 Thirdparty.js 的代码

function ThirdParty() {
  return (
    <div>
      <label>ThirdParty</label>            
    </div>
 )
}

export default ThirdParty;

 ****layout.js****

import {
  BrowserRouter as ReactRouter,
  Switch as ReactSwitch,
  Route as ReactRoute,
} from "react-router-dom";

import ThirdParty from "./ThirdParty.js";
    
export default function Layout() {
  return (
    <div>
      <ReactRouter>
        <MainToolBar />
          <ReactSwitch>
          <ReactRoute exact path="/" component={SignInUp}> 
          </ReactRoute>         
          <ReactRoute exact path="/thirdparty" component= 
          {ThirdParty}></ReactRoute>
        </ReactSwitch>
      </ReactRouter>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*Bar 5

Context APIredux都是很好的解决方案。这样,您可以编写一个简单的效果钩子来更新工具栏标题上下文/调度 redux 操作来更改它。该钩子将在由组件呈现的主要组件内部被调用Route

另一种解决方案(但可能不太一致)是根据路径为可选工具栏标题创建映射对象。这样您就可以使用react-router-domuseLocation钩子识别路径,并更改效果中的标题。例如,

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";

const titles = {
  "/": "ERP System",
  "/thirdparty": "Third Party"
};

...
// Inside Toolbar component
const location = useLocation();
const [title, setTitle] = useState(titles["/"]);

useEffect(() => {
  setTitle(titles[location.pathname]);
}, [location.pathname]);

...
Run Code Online (Sandbox Code Playgroud)

如果您的路径依赖于 ID 值,则效果内部将需要更复杂的逻辑。