react-router - withRouter导致this.props.router未定义

时间:2016-06-01 11:55:15

标签: reactjs react-router

我已按照https://github.com/reactjs/react-router/blob/cbdc49442aba5cc6f225ff5546ac5f4a217fa4ec/upgrade-guides/v2.4.0.md上的文档进行操作,但我正在努力使用新的withRouter高阶组件访问this.props.router。

import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router';
import * as actionCreators from '../action_creators';

export const ComponentA = withRouter(React.createClass({
  componentDidMount() {
    console.log(this.props.router); //returns undefined
  },
  render() {
    return (
      <div></div>
    );
  }
}));

//map redux state to props
function mapStateToProps(state) {
  return {
    views: state.main.get('views')
  };
}

export const ComponentAContainer = connect(
  mapStateToProps,
  actionCreators
)(ComponentA);

不幸的是this.props.router总是返回undefined。出于某种原因,它似乎没有作为财产注入。

this.props看起来像这样:

addBranch: function()
addProject: function()
addView: function()
castDeviceAvailable: function()
castDeviceConnected: function()
castDeviceDisconnected: function()
castDeviceUnavailable: function()
closeBurgerMenu: function()
createProject: function()
deleteBranch: function()
deleteProject: function()
deleteView: function()
formValidation: function()
getCastDeviceAuthToken: function()
key: function(...)
get key: function()
loadView: function()
navigateToSettings: function()
newBuild: function()
newBuildSummary: function()
newCastDeviceAuthToken: function()
openBurgerMenu: function()
projectAdded: function()
projectDeleted: function()
projectUpdated: function()
ref: function(...)
get ref: function()
router: undefined
setBuildSummary: function()
setLatestBuilds: function()
setProjects: function()
setState: function()
setThemes: function()
setViews: function()
subscribeToView: function()
toggleBurgerMenu: function()
updateView: function()
viewAdded: function()
viewDeleted: function()
viewUpdated: function()
__proto__: Object  

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您是否尝试过包裹connect?像这样......

export const ComponentAContainer = withRouter(connect(
  mapStateToProps,
  actionCreators
)(ComponentA));

注意:在执行此操作时,您还应删除类定义中的withRouter包装。