2017-04-23 111 views
1

我目前使用themeteorchef/base樣板工程。當我從Meteor/Blaze轉到Meteor/React世界時,這真的很有幫助。將Meteor.user()傳遞給組件?

直接將訂閱數據通過容器傳遞給組件。但是,試圖創建一個基本的配置文件頁面已經非常困難,我覺得我錯過了一些簡單的東西。到目前爲止,我已經設法將用戶對象作爲json字符串傳遞(這並不理想)。

我的問題是 - 什麼是通過一個登錄用戶的信息的反應成分的最佳方式?

在我的容器,我...

import { Meteor } from 'meteor/meteor'; 
import { composeWithTracker } from 'react-komposer'; 
import ViewProfile from '../pages/ViewProfile.js'; 
import Loading from '../components/Loading.js'; 

const composer = ({ params }, onData) => { 
    const currentUser = JSON.stringify(Meteor.user()); 
    onData(null, { currentUser }); 
}; 

export default composeWithTracker(composer, Loading)(ViewProfile); 

而我的組件是一個簡單的顯示...

import React from 'react'; 
import NotFound from './NotFound'; 

const ViewProfile = ({ currentUser }) => { 
    return currentUser ? (
    <p>{ currentUser }</p> 
) : <NotFound />; 
}; 

ViewProfile.propTypes = { 
    currentUser: React.PropTypes.string 
}; 

export default ViewProfile; 

回答

1

終於搞定了!

通過容器傳遞Meteor.user(反應數據)仍然是正確的方法,它已經到達組件,但是,在我的組件中,我只需要引用特定的對象值(字符串或數組)。

所以在我的容器:

import { composeWithTracker } from 'react-komposer'; 
import ViewProfile from '../pages/ViewProfile.js'; 
import Loading from '../components/Loading.js'; 

const composer = (params, onData) => { 
    const user = Meteor.user(); 

    if (user) { 
     const currentUser = { 
      fname: user.profile.name.first, 
      lname: user.profile.name.last, 
      email: user.emails[0].address 
     } 

     onData(null, { currentUser }); 
    } 

export default composeWithTracker(composer, Loading)(ViewProfile); 

然後在我的組件:

import React from 'react'; 
import NotFound from './NotFound'; 

const ViewProfile = ({currentUser}) => { 
    //console.log(currentUser); 

    return (currentUser) ? (
    <p>{ currentUser.fname }</p> 
    <p>{ currentUser.lname }</p> 
    <p>{ currentUser.email }</p> 
) : <NotFound />; 
}; 

ViewProfile.propTypes = { 
    currentUser: React.PropTypes.object, 
}; 

export default ViewProfile; 
0

事實上,你可以訪問 「Meteor.user()」任何地方,所以你不需要從Composer或Parent-Component傳遞它。 因此,在您的簡單組件中,您可以使用:

import React from 'react'; 
import NotFound from './NotFound'; 

const ViewProfile =() => { 
    return (Meteor.user()) ? (
    <p>{JSON.stringify(Meteor.user())}</p> 
) : <NotFound />; 
}; 

export default ViewProfile; 
+1

感謝您的答覆!目前通過該編輯,Meteor.user仍然以undefined形式返回。據我瞭解,Meteor.user()是反應性的,所以在初始加載時它將是未定義的。我需要以某種方式檢查用戶集合的.ready()嗎? – JenLikesCode

+0

看來,有2例爲其中Meteor.user() – thinhvo0108

+0

(對不起,我輸錯)返回undefined看來,有2例爲其中Meteor.user()返回undefined:1是用戶沒有登錄,和2在用戶剛剛登錄之後,您的頁面在Meteor.user()可以被訪問之前加載!實際上,在以前的版本中使用composer是很常見的,也是處理這個用戶的好方法。你自己更新的代碼現在很好。 – thinhvo0108