簡體   English   中英

如何在沒有道具的情況下從反應中獲得當前路線

[英]How to get the current route from react without props

我試圖根據路線來顯示/隱藏按鈕以做出反應。

在home.js中,我呈現了以下內容:

<Route exact path="/" render={()=> <TotalStuff totalStuff={totalStuff} />} />
<Link to="/addStuff"><button>Add Stuff</button></Link>
<Route path="/addStuff" exact component={AddStuff} />

當route為“ /”時,它僅使用“添加填充”按鈕和一些文本內容來呈現addStuff組件。

但是我想在AddStuff組件中隱藏“添加材料”按鈕。

嘗試使用window.location.pathname時,不會隨着路由器的更改而更新。

我也嘗試了withRouter 但我正在尋找更好的直接方法(如果有)。

謝謝。

您可以將Link放置在第一個Route組件的render prop /addStuff ,以使其不顯示在/addStuff路徑上。

<Route
  exact
  path="/"
  render={() => (
    <div>
      <TotalStuff totalStuff={totalStuff} />
      <Link to="/addStuff">
        <button>Add Stuff</button>
      </Link>
    </div>
  )}
/>
<Route path="/addStuff" exact component={AddStuff} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM