簡體   English   中英

在react-router渲染功能中訪問URL參數

[英]Accessing URL param in react-router render function

這是一個快速的問題,但到目前為止我還沒有找到解決方案:

我想使用render方法使用react-router v4訪問URL參數。 到目前為止我發現的所有東西都只傳遞了這樣的組件:

<Route path="/:id" component={Child} />

但是我想使用這樣的render方法:

<Route path="/:id" render={() => (<Wrapper> <Child /> </Wrapper>)} />

但是,當我嘗試使用我的Child組件中的props.match.params.id訪問id參數時, match prop未定義。

知道如何使用渲染功能並仍然訪問url參數嗎?

你需要將路徑從Route傳遞給Child

<Route path="/:id" render={(props) => (<Wrapper> <Child {...props} /> </Wrapper>)} />

要么 :

<Route path="/:id" render={(props) => (<Wrapper> <Child id={props.match.params.id} /> </Wrapper>)} />

您可以使用location.search在URL中獲取該查詢字符串,並從location.pathname獲取路徑

<Route
      path="/about"
      render={({ location, history }) => (
           <div>
                 <p>We are at: {location.pathname}</p>
                 <p>Query string is: {location.search}</p>
           </div>
      )}
/>

暫無
暫無

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

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