Reactjs MeteorJS:在客户端获取用户配置文件
所以,这个问题已经被很好地记录下来了,但我在这里,再次陷入困境 在服务器端,我发布了:Reactjs MeteorJS:在客户端获取用户配置文件,reactjs,meteor,Reactjs,Meteor,所以,这个问题已经被很好地记录下来了,但我在这里,再次陷入困境 在服务器端,我发布了: Meteor.publish('userData', function(){ if (!this.userId) { return null; } return Meteor.users.find({}, {fields: {'profile': 1}}); }); 在客户端路由器订阅方面,我有: this.register('userData', Meteor.subscribe('userData')
Meteor.publish('userData', function(){ if (!this.userId) { return null; }
return Meteor.users.find({}, {fields: {'profile': 1}}); });
在客户端路由器订阅方面,我有:
this.register('userData', Meteor.subscribe('userData'));
然后在我的客户代码中,我有:
if (Meteor.userId()) {
var profile = Meteor.users.find(Meteor.userId()).profile;
console.log(profile); // I keep getting undefined...
我没有使用自动发布或不安全的软件包
我在mongodb集合中的数据如下所示:
{"_id" : "...", profile: { "password" : { "network" : "...", "picture" : "none" } }
我的错误是:
Uncaught TypeError: Cannot read property 'password' of undefined
想法?我认为问题在于这个问题
var profile = Meteor.users.find({_id: Meteor.userId()}).profile;
或者这也行
var profile = Meteor.user().profile;
因此,事实证明,我的大部分代码都是正确的,但正如ghybs在上面指出的,我仍然需要等待用户数据。这是我的工作代码:
// in publish.js on the server
Meteor.publish('userData', function(){ if (!this.userId) { return null; }
return Meteor.users.find({_id: this.userId}, {fields: {'profile': 1}}); });
// in routes.jsx using FlowRouter
// after importing all the module external data
FlowRouter.route('/',{subscriptions:function(){
this.register('getUser', Meteor.subscribe('userData'));
}, action() {
mount(...etc...
// Keep in mind that I am using TrackerReact NPM to handle re-renders...
// in my component
if (FlowRouter.subsReady("getUser")) {
// this returns an array with one object
var userObject = Meteor.users.find({_id: Meteor.userId()}).fetch()[0];
用户配置文件将自动发布到客户端,您无需编写自定义发布来发送它。这就是为什么您不应该在配置文件中存储敏感的用户信息。你可以把那本书扔掉 要访问组件中的配置文件,您只需将组件或整个应用程序包装在数据容器中,然后将配置文件发送到组件。这样做的原因是容器是被动的,因此组件将加载,直到meteor用户对象准备就绪,然后您可以立即访问存储在概要文件中的内容 创建容器:
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Navigation } from '/imports/ui/components/user-navigation/Navigation';
export default createContainer(() => {
const loading = !Meteor.user();
const user = Meteor.user();
return { loading, user };
}, Navigation);
组件中的访问配置文件:
import React, { Component } from 'react';
export class Navigation extends React.Component {
constructor(props) {
super(props);
}
render() {
const { user, loading } = this.props;
return (
loading ? <Loading /> :
<div className="navigation">
User's name is: { user.profile.firstname }
</div>
)
}
};
试着替换
var profile = Meteor.users.find({_id: Meteor.userId()}).profile;
与
你什么时候执行你的客户端代码?@ghybs应用程序什么时候启动你在等待你的“用户数据”订阅准备好吗?@ghybs我不这么认为。我敢打赌你在未登录时正在检查Meteor.userId。只有在这种情况下,你可能会得到未定义或空。不,仍然得到“未定义”嘿,谢谢你的回答。在我的特定实例中,这可能不适用,因为我已经在使用TrackerReact而不是react meteor数据进行反应。另外,当我使用FlowRouter时,我可以通过我的路由进行订阅,然后使用FlowRouter.subsReady等待订阅
var profile = Meteor.users.findOne({_id: Meteor.userId()}).profile;