reactjs - 通过react-router-4导航后未获取路由参数

标签 reactjs redux react-router-v4

通过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>;
  }

最佳答案

结合使用 componentWillReceivePropscomponentDidMount 生命周期方法。

当组件第一次渲染时,在 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/

相关文章:

javascript - 根据访问的部分显示搜索栏(React.js)编辑

javascript - create-react-app 的开发服务器不会自动刷新

reactjs - 使用 react 路由器在所有页面上创建公共(public)标题和侧边栏

reactjs - 如何防止导航栏菜单在导航时重新渲染? react 路由器 v4

javascript - 如何在 React 中访问 DOM 元素? React 中 document.getElementById() 的等价物是什么

reactjs - 我无法将下一个 js 链接添加到 mui appbar

reactjs - Redux - 如何从另一个 Action 创建者内部调用一个 Action 创建者?

redux - mapStateToProps 和 mapDispatchToProps : getting IDE to "see" the props

javascript - 如何让这段代码看起来更好

javascript - 如何在客户端使用 React 的 BrowserRouter,在服务端使用 Java REST API (Spring Boot)?