【问题标题】:execute route change from siblings component in React Router V4从 React Router V4 中的兄弟组件执行路由更改
【发布时间】:2018-11-15 07:11:30
【问题描述】:

我正在学习 React.js。我正在使用 React 路由器版本 4.3.1 和 React 路由器 dom 4.3.1。

我当前的应用结构如下所示。

<React.Fragment>
  {/* sidebar component */}
  <SideBar store = {Mystore} />
  <div className="main-panel">
  {/* navbar component */}
  <NavBar store = {Mystore}/>
  {/* content component */}
  <Content store = {Mystore}/>
  {/* footer component */}
  </div>
</React.Fragment>

在我的内容组件中,我设置了一个路由器,如下所示。

<BrowserRouter> 
  <React.Fragment> 
  <Route exact path="/phoenix/public" component={Login} /> 
  <ProtectedRoute exact path="/phoenix/public/sample" component={SamplePage} /> 
  <ProtectedRoute exact path="/phoenix/public/view_ticket" component={ViewTicket} /> 
  <ProtectedRoute exact path="/phoenix/public/create_ticket" component={CreateTicket} /> 
  <ProtectedRoute exact path="/phoenix/public/dashboard" component={Dashborad} /> 
  </React.Fragment> 
</BrowserRouter>

这里的ProtectedRoute是一个功能组件,它检查用户是否被认证并返回一个Route

我的侧边栏有一些 a 标签,如下所示。

<li> 
  <a href="dashboard"> 
  <i className="ti-panel" /> 
  <p>Dashboard</p> 
  </a> 
</li>

我的目标是导航到不同的路线,而无需从侧边栏点击页面刷新。但是点击 href 会重新加载页面,并且我在 Mobx 中的所有状态都会刷新。我尝试 Redirect 但无法获得兄弟组件中所述的路由器(内容是侧边栏的兄弟)。我不知道如何实现这一目标。

【问题讨论】:

  • 您是否尝试过使用Link?
  • 你试过 navigationOption 道具吗?
  • 我尝试使用链接,但我想它需要一个路由器,但我的侧边栏组件没有路由器。如果我的路由器是在内容中设置的,我如何在侧边栏组件中使用链接?

标签: reactjs react-router-v4 react-router-dom


【解决方案1】:

正如您问题的 cmets 中所述,常规的 &lt;a&gt; 标签将不起作用,并刷新页面。所以你需要使用Link 或 NavLink。

如果你想让它在你的侧边栏(子组件)中工作,你需要将 &lt;BrowserRouter&gt; 包裹在你想要使用路由的所有组件周围。

例如像这样(使用您的代码):

<BrowserRouter>
<React.Fragment>
  {/* sidebar component */}
  <SideBar store = {Mystore} />
  <div className="main-panel">
  {/* navbar component */}
  <NavBar store = {Mystore}/>
  {/* content component */}
  <Content store = {Mystore}/>
  {/* footer component */}
  </div>
</React.Fragment>
</BrowserRouter>

您的侧边栏将是这样的:

<React.Fragment>
    <Link to="/dashboard">Dashboard</Link> 
    ...
</React.Fragment>

然后在您的内容组件中。你需要删除&lt;BrowserRouter&gt;

【讨论】:

【解决方案2】:

按照@PreDinnerSnack 的建议,我通过如下所示的 BrowserRouter 解决了我的问题。

<BrowserRouter>
<React.Fragment>
  {/* sidebar component */}
  <SideBar store = {Mystore} />
  <div className="main-panel">
  {/* navbar component */}
  <NavBar store = {Mystore}/>
  {/* content component */}
  <Content store = {Mystore}/>
  {/* footer component */}
  </div>
</React.Fragment>
</BrowserRouter>

然后我在我的侧边栏组件中使用了 Navlink。这解决了在不刷新页面的情况下导航到所需路线的问题。但后来我遇到了另一个问题,因为内容没有根据路线刷新。

对于这个问题,我发现 Mobx 的观察者 HOC 正在干扰我的路由器。我必须如下用 withRouter 包装我的内容来解决这个问题。

withRouter(observer(Content));

我希望我的解决方案能派上用场,因为我在网上找不到像我一样的 React Router 实现示例的教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2017-08-20
    • 2018-06-22
    • 1970-01-01
    相关资源
    最近更新 更多