2017-04-07 42 views
1

導航後經過this.props.history.push我沒有在component中獲得route params在導航via react-router-4後未得到路由參數

我有兩個路線上呈現的單個component

因此,從一條路線到另一條是component update,我沒有得到它的route params

如果刷新頁面,我得到的route params

this.props.history.push(`/pois/select/${lastAction.payload.poiID}`) 

我的路由組件。

class Routes extends React.Component { 
    render() { 
    return <div> 
      <Switch > 
       <Route exact path="/pois/" component={ POIS } mode='view' /> 
       <Route exact path="/pois/select/:poiID" component={ POIS } mode='select' /> 
       <Route exact path="/pois/create" component={ POIS } mode='create'/> 
       <Route exact path="/pois/update/:poiID" component={ POIS } mode='update'/> 
      </Switch> 
     </div>; 
    } 
+1

在哪裏打印params的名稱?使用'componentWillReceiveProps'生命方法並使用'console.log(nextProps.params)'它會打印值。這樣'componentWillReceiveProps(nextProps){ \t的console.log(nextProps.params) }' –

+0

@MayankShukla 我可以看到的URL更新,在組件控制檯記錄表明'this.props.match.params'是空對象'{}' –

+0

@MayankShukla 我可以在'componentWillReceiveProps'中看到參數,但是在'componentWillUpdate'調用的函數中看不到然後我想在執行前檢查模式是否發生了變化,'ajax'所以我需要'prevprops' –

回答

2

使用componentWillReceivePropscomponentDidMount生命週期方法的組合。

當第一次組件呈現做API調用內componentDidMount方法,並獲取數據,如:

componentDidMount(){ 
    // ajax call to fetch data then do setState to store in state variable 
} 

當道具任何事物的變化,componentWillReceiveProps方法將被調用下一次,做API請撥打電話,如下所示:

componentWillReceiveProps(nextProps){ 
    console.log(nextProps.params, this.props.params); 
    // nextProps.params will print the new params values 
    // this.props.params will print the old params values 
    // ajax call to fetch data then do setState to store in state variable 
} 
+0

仍然面臨任何問題呢? –

+0

不,它的工作!謝謝! –