2017-04-23 124 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