TrackerReact 容器 - 用户设置了 profile.avatar ,但控制台说它未定义

TrackerReact Container - User has profile.avatar set but console says it's undefined

本文关键字:控制台 未定义 avatar profile 容器 用户 设置 TrackerReact      更新时间:2023-09-26

我有一个名为ProfileSettingsContainer的TrackerReact容器,它将Meteor.user()返回给user()函数并将其传递给ProfileSettings组件。我的最终目标是为用户的个人资料创建一个设置页面,用户可以在其中更改其头像并更新其他信息。这是我的代码。

profile_settings_container.js

import React, { Component } from 'react';
import TrackerReact from 'meteor/ultimatejs:tracker-react';
import ProfileSettings from './profile_settings';
export default class ProfileSettingsContainer extends TrackerReact(Component) {
  user(){
    return Meteor.user();
  }
  render() {
    let user = this.user;
    return (
      <ProfileSettings user={user} />
    );
  }
}

profile_settings.js

import React, { Component } from 'react';
import { Link } from 'react-router';
export default class ProfileSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      avatar: props.user.profile.avatar || "../../../public/user-default.svg"
    }
  }
  componentWillMount(){
    // we create this rule both on client and server
    Slingshot.fileRestrictions("avatar", {
      allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
      maxSize: 2 * 500 * 500
    });
  }
  upload(){
    var userId = Meteor.user()._id;
    var metaContext = {avatarId: userId};
    var uploader = new Slingshot.Upload("UsersAvatar", metaContext);
    uploader.send(document.getElementById('input').files[0], function (error, downloadUrl) { // you can use refs if you like
      if (error) {
        console.error('Error uploading', uploader.xhr.response);
        alert (error); 
      }
      else {
        Meteor.users.update(Meteor.userId(), {$set: {"profile.avatar": downloadUrl}}); 
      }
      this.setState({avatar: downloadUrl});
    }.bind(this));
  }
  formSubmit(){
    let avatarUrl = this.state.avatar;
    Meteor.users.update( {_id: Meteor.userId() }, {
      $set: {'profile.avatar': avatarUrl}
    });
  }
  render() {
    return (
      <div>
        <div className="sticky-header">
          <h3>Settings</h3>
        </div>
        <form>
          <div className="row well">
           <div className="col-md-6">
              <div className="form-group">
                <label htmlFor="exampleInputFile">File input</label>
                <input type="file" id="input" onChange={this.upload.bind(this)} />
                <p className="help-block">Image max restriction: 2MB, 500x500. Cropped: 200x200</p>
              </div>
            </div>
            <div className="col-md-6 utar-r"> 
              <img src={this.state.avatar} height="200" width="200" alt="..." className="img-rounded" />
            </div>
            <div className="form-group">
              <button className="btn btn-lg btn-primary btn-block" type="submit" onClick={this.formSubmit.bind(this)}>Update Profile</button>
            </div>
          </div>
        </form>
        <footer className="sticky-footer">
          <Link to="/app/profile">
            <button className="profile-edit bg-black">
                <h3>Cancel</h3>
            </button>
          </Link>
          <Link to="">
            <button className="profile-edit">
                <h3>Save Changes</h3>
            </button>
          </Link>
        </footer>
      </div>
    );
  }
} 

这是我在加载设置页面时遇到的控制台错误:profile_settings.js:11Uncaught TypeError: Cannot read property 'avatar' of undefined

除此之外,我还检查了RoboMongo,可以确认user.profile.avatar存在。我在signup组件的Accounts.createUser()函数中分配了"/user-default.svg"的默认图像。

用户可能尚未加载(定义),因此只需像if (user) return(<ProfileSettings user={user}/>) else return ""一样放置 smth