与createContainer一起使用withRouter并使用历史记录

时间:2017-10-12 23:12:26

标签: reactjs meteor react-router-dom

我正在使用Meteor / React

进行注销功能
import React from 'react';
import { Accounts } from 'meteor/accounts-base';
import createHistory from 'history/createBrowserHistory';
import propTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { createContainer } from 'meteor/react-meteor-data';

const PrivateHeader = (props) => {
  return (
    <div className="header">
      <div className="header__content">
        <h1 className="header__title">{props.title}</h1>
      <button className="button button--link-text" onClick={ props.handleLogout() }>Logout</button>
      </div>
    </div>
  );
};

PrivateHeader.propTypes = {
  title: propTypes.string.isRequired,
  handleLogout: propTypes.func.isRequired
};

export default withRouter(createContainer(() => {
  return {
    handleLogout: () => {
      Accounts.logout(),
      this.props.history.push('/')
    }
  };
}, PrivateHeader));

但是我收到错误

Exception in delivering result of invoking 'login': TypeError: Cannot read property 'history' of undefined
    at Object.handleLogout (http://localhost:3000/app/app.js?hash=e7e6866f8eccc90d612186214db7d5c0717e09d5:843:38)
    at PrivateHeader (http://localhost:3000/app/app.js?hash=e7e6866f8eccc90d612186214db7d5c0717e09d5:828:26)
    at http://localhost:3000/packages/modules.js?hash=4b565562fa4100dc773fad2b7836f486fe1cb6aa:11904:16

我不确定如何解决这个错误。我试过使用const history = createHistory()没有效果。

我使用的依赖项是:

 "dependencies": {
    "babel-runtime": "^6.20.0",
    "history": "^4.7.2",
    "meteor-node-stubs": "~0.2.4",
    "moment": "^2.18.1",
    "prop-types": "^15.5.10",
    "react": "^15.6.2",
    "react-addons-pure-render-mixin": "^15.6.2",
    "react-dom": "^15.6.1",
    "react-router": "^4.1.2",
    "react-router-dom": "^4.1.2",
    "simpl-schema": "^0.3.2"
  },

1 个答案:

答案 0 :(得分:0)

我看到你正在使用React Router DOM。为什么不使用'react-router'中的browserHistory方法?

import { browserHistory } from 'react-router';

然后

Accounts.logout();
browserHistory.push('/');