2017-04-07 48 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

不,它的工作!谢谢! –