0

我目前正在一个项目中使用 react-router-redux,除了我不知道如何访问 react-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

4

1 回答 1

2

您正在.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装饰器获得的已连接的组件。顺便说一句,这是避免使用装饰器的另一个原因!

于 2016-04-16T02:11:27.400 回答