我有一个具有以下简化结构的React应用程序:
function App(props) {
return (
<Navbar />
<Router>
<Route exact path="/profile/" component={Profile} />
<Route exact path="/" component={Home} />
</Router>
);
}在Navbar组件中,我有一个logout按钮,这意味着我需要:
我尝试使用onClick of那个按钮并使用this.props.history.push('/')更改路径,但是这不起作用(它抱怨history是undefined),因为我的导航条是在路由器之外定义的。
我的问题是,是否可以将Navbar移动到路由器组件中,并在所有页面中相同时重复它?或者有什么防重复的解决方案可以用来改变我的浏览器路径?
发布于 2020-05-08 18:37:40
路由侦听由路由器上下文提供的历史api,而且由于Navbar是在其外部呈现的,所以它们不反映更改。
解决方案是将路由器封装在导航栏周围,并将navbar呈现为默认路由。
function App(props) {
return (
<Router>
<>
<Route component={Navbar}/>
<Route exact path="/profile/" component={Profile} />
<Route exact path="/" component={Home} />
</>
</Router>
);
}发布于 2020-05-08 18:41:36
将<Navbar>插入路由器是很好的。我的安排往往是
<Router>
<div className="app-container">
<Navigation />
<div className="content">
<Switch>
(Routes go here)
</Switch>
</div>
</div>
</Router>发布于 2020-05-08 18:45:45
是!尝试在路由器中使用<Switch>,在你的海军中使用<Link>
export default function App() {
return (
<Router>
<Navbar />
// inside Navbar try using <Link to="/">Logout</Link>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
}https://reacttraining.com/react-router/web/guides/quick-start
https://stackoverflow.com/questions/61685774
复制相似问题