可以't访问上下文.带有react路由器redux的路由器

Can't access context.router with react-router-redux

本文关键字:路由器 react 带有 redux 上下文 访问 可以      更新时间:2023-10-18

我目前正在一个项目中使用react router redux,除了我不知道如何访问react router-router之外,一切都很好。

@connect((state, props) => {
    return  {
                notification:state.getIn(['_display', 'notification']),
                loadingScreen:state.getIn(['_display', 'loadingScreen']),
                route:props.location.pathname
            };
})
export default class Consultation extends React.Component {
    constructor(props,context) {
        super(props, context);
        console.log(context.router);
    }
    componentDidMount(){
        const { router } = this.context;
        .....
    }
    render(){
     ....
    }
}
Consultation.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store:React.PropTypes.object
};

this.context.router总是未定义的,我已经尝试了很多事情,但都没有成功

我正在使用react 0.14.6、redux 3.0.2、react router 2.0.0、react router redux 4.0.0

您将.contextTypes放在connect()返回的组件上,而不是放在您自己的组件上。这就是为什么上下文不可用于组件的原因。

试试这个:

class Consultation extends React.Component {
    constructor(props, context) {
        super(props, context);
        console.log(context.router);
    }
    componentDidMount(){
        const { router } = this.context;
        .....
    }
    render(){
     ....
    }
}
Consultation.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store:React.PropTypes.object
}
export default connect(...)(Consultation)

请注意,我们首先指定contextTypes,并导出连接的组件,而不是将contextTypes分配给从@connect装饰器获得的已连接组件。顺便说一句,这是避免装饰师的另一个原因!