【问题标题】:How to get which route called a component如何获取哪个路由称为组件
【发布时间】:2020-02-20 11:27:38
【问题描述】:

我正在使用 react-route-dom,我想实现这个配置:

<Route exact path='/test/:id' component={MyComponent}/>
<Route exact path='/test2/:id' component={MyComponent}/>

然后在 MyComponent 中,我想根据调用它的路由做一些不同的事情。

const MyComponent = ({info: {param}, info2: {param1, param2}}) => {


  return (
    <div>

    </div>

  )
}

MyComponent.propTypes = {
  info: PropTypes.object.isRequired,
  info2: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  info: state.info,
  info2: state.info2
});

export default connect(mapStateToProps, {})(MyComponent);

如何获取测试或 test2 参数?

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    您可以使用 props.location 访问整个路径

    【讨论】:

      【解决方案2】:

      你可以通过 props 发送:

      <Route exact path='/test/:id'>
        <MyComponent route={'test'} />
      </Route>
      

      【讨论】:

      • 这行得通,如何使用钩子获取组件中的路由道具?
      • 为什么要使用钩子?只需使用道具。
      • 我的意思是我使用的是连接redux的函数组件
      • 我改变了一点问题以更好地展示我正在尝试做的事情
      • const MyComponent = ({info: {param}, info2: {param1, param2}, route})
      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      相关资源
      最近更新 更多