2017-05-22 42 views
12

React-Router v4中如何傳遞參數this.props.history.push('/page')如何在react-router v4中將history.push傳遞給params?

.then(response => { 
     var r = this; 
     if (response.status >= 200 && response.status < 300) { 
      r.props.history.push('/template'); 
      }); 
+0

所呈現的組件由'Route'應獲得'this.props.location','this.props.history',等等。我認爲你不需要在v4中使用'ref'。嘗試做'this.props.history.push('/ template');' – saadq

+0

它不是ref,它是指向這個的變量; this.props.history.push( '/模板');帶我到下一頁,但我想通過他們的道具。 – IshanGarg

+0

您正試圖將'props'傳遞給匹配路由的組件?我認爲[這個GitHub線程](https://github.com/ReactTraining/react-router/issues/4105)解決您的問題。 – saadq

回答

33

首先,你不必做if statementvar r = this;,因爲這是指回調本身,這因爲您使用箭頭功能是指陣營組件上下文的語境。

根據該文檔:

歷史對象通常具有以下屬性和方法:

  • 長度 - (數字)條目的歷史堆棧
  • 動作數 - (字符串)當前操作(PUSH,REPLACE或POP)
  • location - (object)當前位置。可能有以下特性:

    • 路徑 - (string)的URL
    • 搜索的路徑 - (string)的URL查詢字符串
    • 哈希 - (string)的URL散列片段
    • 狀態 - (字符串)特定於位置的狀態,提供給例如當這個位置被壓入 堆棧時,推(路徑,狀態)。僅在瀏覽器和內存歷史記錄中可用。
  • 推(路徑,[狀態]) - (功能)將一個新條目到歷史堆棧
  • 取代(的路徑,[狀態]) - (功能)替換歷史堆棧
  • 上的當前條目
  • 去(N) - (功能)由n個條目
  • GoBack的()移動在歷史堆棧指針 - (功能)等同於去(-1)
  • goForward() - (功能)等同於去(1)
  • 塊(提示) - (功能)阻止導航

所以在導航的同時,你可以通過通過道具來歷史的物體,像

this.props.history.push({ 
    pathname: '/template', 
    search: '?query=abc', 
    state: { detail: response.data } 
}) 

或類似的路段組件

<Link to={{ 
     pathname: '/template', 
     search: '?query=abc', 
     state: { detail: response.data } 
    }}> My Link </Link> 

,然後在其中呈現與/template組件路線,您可以訪問通過的道具,如

this.props.location.state.detail 

另請注意,使用道具的歷史記錄或位置對象時,您需要將組件連接到withRouter

按照文檔:

withRouter

你可以訪問歷史記錄對象的屬性,並通過withRouter高次成分最接近 <Route>'s匹配。 withRouter 將在每次路線更改時重新呈現其組件,其中 與<Route>呈現props: { match, location, history }相同。

+0

正確答案。 –

0

附加組件信息獲取查詢參數。

const queryParams = new URLSearchParams(this.props.location.search); 
console.log('assuming query param is id', queryParams.get('id'); 

有關URLSearchParams更多信息檢查此鏈接 URLSearchParams

+0

這與React Router 4沒有任何關係。 –

相關問題