通过this.props.history.push
导航后,我没有在组件
中获取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>;
}
最佳答案
结合使用 componentWillReceiveProps
和 componentDidMount
生命周期方法。
当组件第一次渲染时,在 componentDidMount
方法中调用 api,并获取数据,如下所示:
componentDidMount(){
// ajax call to fetch data then do setState to store in state variable
}
下次当 props 发生任何变化时,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
}
关于reactjs - 通过react-router-4导航后未获取路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275485/