2017-10-12 81 views
0

我在註銷功能正與流星/陣營使用withRouter與createContainer和使用歷史

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" 
    }, 

回答

0

我看你是使用路由器作出反應DOM。爲什麼不使用'react-router'中的browserHistory方法?

import { browserHistory } from 'react-router'; 

然後

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

我現在得到一個不能推未定義錯誤的。 – user8768174

+0

@ user8768174你確定你正在運行代碼嗎?你是否刪除了'this.props.history.push('/')'?如果您正確導入'browserHistory',則無法獲得該錯誤。這些錯誤告訴你,你正試圖調用方法'push',對於未定義的東西 –

+1

我終於明白這是一個愚蠢的錯誤,我不得不將其傳遞給createContainer – user8768174