2017-04-01 20 views
3

我目前正面临一个奇怪的问题,其中react-router提供的HOC withRouter未将道具传递给mapStateToProps函数。我在这里做错了吗?react-router withRouter不在mapStateToProps中提供道具?

import React, { Component } from 'react'; 
import { Link, withRouter } from 'react-router'; 
import { connect } from 'react-redux'; 


class ThisClass extends Component { 
    render() { 
     console.log(this.props.router); // Returns object with router keys (params, router, go, routes, ...) 
     // Render stuff 
    } 
} 

const mapStateToProps = (state, props) => { 
    console.log(state); // returns state of redux 
    console.log(props); // returns empty object -> {}, how come this is empty?! 

    return { 
     consultations: patientThisClassSelector(state, props) 
    }; 
} 

export default connect(mapStateToProps)(withRouter(ThisClass)); 

回答

5

你必须注入路由器道具你连接组件以前

为了实现这一目标,你必须使用

export default withRouter(connect(mapStateToProps)(ThisClass)); 

,而不是

export default connect(mapStateToProps)(withRouter(ThisClass));

+0

没想到这一点,这是一般的不好的做法吗?我刚刚读到,丹建议从父组件传递这些类型的道具。 – NealVDV

+0

我不认为这是一个不好的做法。我相信这是做到这一点的正确方法,否则你可能会阻止你的位置变化。你可以在这里阅读,[阻止更新](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/redux.md#blocked-updates) – QoP

0

对于我来说,我试图让我的原始状态的对象,为了这个,我用我的孩子mapStateToProps类。我正在使用React-Redux,这对我很有用。

var connect = require('react-redux').connect; 
var HeaderSection = React.createClass({ 
    render: function() { 
    console.log(this.props); 
    } 
}); 

function mapStateToProps(state) { 
    return state; 
} 

module.exports = connect(mapStateToProps)(HeaderSection); 
相关问题