2016-07-27 27 views
0

我一直在試圖使用Tracker React顯示登錄用戶的用戶名。 我已經刪除了自動發佈軟件包。顯示Meteor.user()。使用跟蹤器的用戶名React

/Client/components/dashboard/sidebar.jsx

import React, {Component} from 'react' 
import TrackerReact from 'meteor/ultimatejs:tracker-react'; 

export default class Sidebar extends TrackerReact(Component) { 

constructor() { 
    super(); 
    this.state = { 
     subscription: { 
      users: Meteor.subscribe('users') 
     } 
    }; 

} 
render() { 
    return( 
    <div> 
      <h1>{Meteor.user().username}</h1> 
    </div> 
); 
} 

/服務器/出版/ userPublications

Meteor.publish("users", function() { 
    return Meteor.users.find(); 
}); 

我得到一個空對象,而console.log(Meteor.user())。但是,我可以使用Meteor DevTools查看當前的用戶名。

我錯過了什麼拼圖塊?

+0

難道你不需要導入流星?像'meteor/meteor''的導入{Meteor}? – CodeChimp

+0

我解決了這個問題[鏈接到類似問題](https://stackoverflow.com/questions/43417385/meteorjs-get-user-profile-on-client-side/43422269#43422269) – Daltron

回答

0

我懷疑你可以使用Meteor.user()。用戶名

試試這個

<h1>{{currentUser}}</h1> 
+0

我得到'側邊欄.jsx:29Uncaught ReferenceError:currentUser is not defined' –

+0

我有一個類似的[在這裏回答](https://stackoverflow.com/questions/43417385/meteorjs-get-user-profile-on-client-side/43422269#43422269 ) – Daltron

0

可以以管理其使用createContainer

import { Meteor } from 'meteor/meteor'; 
import React, { Component, PropTypes } from 'react'; 
import { createContainer } from 'meteor/react-meteor-data'; 

export class Sidebar extends Component { 
    static propTypes = { 
    loggedIn: PropTypes.bool.isRequired, 
    loggingIn: PropTypes.bool.isRequired, 
    currentUser: PropTypes.shape({ 
     username: PropTypes.string 
    }) 
    } 
    render() { 
    const { loggingIn, loggedIn } = this.props; 
    return (
     <div> 
     {(() => { 
      if (loggingIn) { 
      return <Loading /> 
      } else if (loggedIn) { 
      // whatever you want here. 
      } else { 
      <h1>Please Log In</h1> 
      } 
     })()} 
     </div> 
    ) 
    } 
} 

export default createContainer(() => ({ 
    user: Meteor.user(), 
    loggedIn: !Meteor.userId(), 
    loggingIn: Meteor.loggingIn() 
}), Sidebar); 

這裏的一些細節:

  • Meteor.loggingIn()是在用戶登錄時運行的反應變量。當發生這種情況,不會有一個用戶對象
  • 您應該創建一個反應容器
+0

很好的回覆! 只是一個小問題。爲什麼你在登錄分配中添加額外的**!**? 我認爲這不是必要的。 ;) –

+0

我有一個類似的[答案](https://stackoverflow.com/questions/43417385/meteorjs-get-user-profile-on-client-side/43422269#43422269) – Daltron