【问题标题】:React Router, access history object from child componentsReact Router,从子组件访问历史对象
【发布时间】:2017-08-01 17:13:24
【问题描述】:

我想在深层嵌套子组件之一中使用history.listen 收听位置变化。

具有this.props.history 的顶级父组件是否应该将道具一直向下传递给子组件?

我使用的是 2.8.1 react-router

如果它允许我轻松地升级到新版本,我愿意升级。

【问题讨论】:

  • React-router 将历史对象作为上下文传递给子节点到深层叶节点。使用上下文获取历史对象
  • 如何在 react-router-dom v4 中实现?

标签: reactjs react-router


【解决方案1】:
import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render() {
    // props also has match, location
    const { history } = this.props;
    ...
  }
}

export default withRouter(MyComponent);

【讨论】:

    【解决方案2】:

    您可以通过获取路由器上下文来获得history

    import React, {PropTypes} from 'react';
    
    class myComponent extends React.Component {
       render() {
          console.log(this.context.history);
       }
    }
    
    myComponent.contextTypes = {
       history: PropTypes.object
    }
    
    export default myComponent;
    

    【讨论】:

    • 我认为您使用的是不同的版本,即使在父组件中我也无法获取 this.context.history。
    • 嗯...奇怪。我已经用 2.8.1 测试了这段代码。版本,它工作。确保您在 contextTypes 中定义了 history 并为 组件定义了 history 属性
    猜你喜欢
    • 2017-03-20
    • 2017-08-31
    • 2018-11-07
    • 2017-08-23
    • 1970-01-01
    • 2023-03-30
    • 2019-08-03
    • 1970-01-01
    • 2018-01-26
    相关资源
    最近更新 更多