具有Material UI的React Router无法呈现组件

时间:2020-09-15 22:17:06

标签: reactjs material-ui

该组件无法渲染,我只看到了该组件,仅此而已。

这是App.js

import { BrowserRouter, Route, Switch } from "react-router-dom";
import Header from "./app/Header";
import HomePage from "./app/HomePage";
import Tasks from "./app/tasks/Tasks";
import { Counter } from "./features/counter/Counter";

export default function App() {
   return (
      <BrowserRouter>
         <Switch>
            <Header/>
            <Route exact path='/' component={HomePage} />
            <Route path='/counter' component={Counter} />
            <Route path='/tasks' component={Tasks}/> 
         </Switch>
      </BrowserRouter>
   );
}

这是Header.js中的Material UI列表,其中有链接。

            {["Add Client", "Edit existing", "Tasks", "Next renewals"].map((text, index) => (
               <Link
                  style={{ textDecoration: "none", color: "inherit" }}
                  to={`/${text.toLowerCase().replace(" ", "-")}`}
               >
                  <ListItem button key={text}>
                     <ListItemIcon>
                        {index % 2 === 0 ? <PostAddIcon/> : <EditIcon/>}
                     </ListItemIcon>
                     <ListItemText primary={text} />
                  </ListItem>
               </Link>
            ))}
         </List>

2 个答案:

答案 0 :(得分:0)

Header组件必须位于另一个组件内,而不位于路由器内部

答案 1 :(得分:0)

将Header组件放置在Switch外部,以便在整个应用程序中都相同:

function App() {
  return (
    <BrowserRouter>
      <Header/>
      <Switch>
        <Route exact path='/' component={HomePage} />
        <Route path='/counter' component={Counter} />
        <Route path='/tasks' component={Tasks}/> 
      </Switch>
    </BrowserRouter>
  )
}