首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用onClick更改非路由器组件的路径

使用onClick更改非路由器组件的路径
EN

Stack Overflow用户
提问于 2020-05-08 18:34:10
回答 3查看 331关注 0票数 1

我有一个具有以下简化结构的React应用程序:

代码语言:javascript
复制
function App(props) {
    return (
        <Navbar />
        <Router>
            <Route exact path="/profile/" component={Profile} />
            <Route exact path="/" component={Home} />
        </Router>
    );
}

Navbar组件中,我有一个logout按钮,这意味着我需要:

  1. 从存储中删除身份验证令牌(只需为一般情况执行一个逻辑),并将
  2. 路由用户删除到登录页面.

我尝试使用onClick of那个按钮并使用this.props.history.push('/')更改路径,但是这不起作用(它抱怨historyundefined),因为我的导航条是在路由器之外定义的。

我的问题是,是否可以将Navbar移动到路由器组件中,并在所有页面中相同时重复它?或者有什么防重复的解决方案可以用来改变我的浏览器路径?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-08 18:37:40

路由侦听由路由器上下文提供的历史api,而且由于Navbar是在其外部呈现的,所以它们不反映更改。

解决方案是将路由器封装在导航栏周围,并将navbar呈现为默认路由。

代码语言:javascript
复制
function App(props) {
    return (
       <Router>
          <>
            <Route component={Navbar}/>
            <Route exact path="/profile/" component={Profile} />
            <Route exact path="/" component={Home} />
          </>
        </Router>
    );
}
票数 0
EN

Stack Overflow用户

发布于 2020-05-08 18:41:36

<Navbar>插入路由器是很好的。我的安排往往是

代码语言:javascript
复制
<Router>
    <div className="app-container">
      <Navigation />
      <div className="content">
        <Switch>
          (Routes go here)
        </Switch>
      </div>
    </div>
</Router>
票数 2
EN

Stack Overflow用户

发布于 2020-05-08 18:45:45

是!尝试在路由器中使用<Switch>,在你的海军中使用<Link>

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61685774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档