【问题标题】:Cannot read property 'currentUser' of undefined无法读取未定义的属性“currentUser”
【发布时间】:2016-05-28 01:38:09
【问题描述】:

重定向到仪表板页面时出现错误。错误出现在导航栏组件中。我使用过 ReactMeteorData mixin。我的代码是

const ReactMeteorDataWrap = (BaseComponent)=>{
    return class ExportClass extends Component { 
        getMeteorData(){
            let data = {};
            console.log(Meteor.user()); // shows undefined in console
            data.currentUser = Meteor.user();
            console.log('data',data);
            return data;
        }
        render(){
            return <BaseComponent getMeteor={()=>this.getMeteorData()} 
                 {...this.props}></BaseComponent>
        }
    }
}

export default ReactMeteorDataWrap;

使用 ReactMeteorData 混合的 Navbar.jsx

import ReactMeteorDataWrap from '../ReactMeteorDataWrap.jsx';

class Navbar extends Component {
    constructor(props){
        super(props);
        this.state = { searchText: '' };
        this.props.getMeteor();
    }
     //getMeteorData() {
    //  this.props.getMeteor();
    //}


    componentDidMount(){
        var users = Meteor.users.find({},{fields:{'profile':1}}).fetch();
        var usernames = [];
        users.map(function(user){
            usernames.push(user.profile.fullname);
        });
        $('#typeahead').typeahead({
            name: 'users',
            local: usernames
        });
    }

    handleSubmit(e){
        e.preventDefault();
        FlowRouter.go('/user/' + (this.refs.searchText.value).trim());
    }

    render() {
         var fullname = '';
        if(this.data.currentUser && this.data.currentUser.profile){
            fullname = this.data.currentUser.profile.firstname + ' ' + this.data.currentUser.profile.lastname; // error is shown here
        }
        return ();
}

export default ReactMeteorDataWrap(Navbar);

我在 ReactMeteorDataWrap 中安慰 Meteor.user() 时未定义,无法在 Navbar.jsx 渲染函数中读取属性“currentUser”。

【问题讨论】:

    标签: javascript node.js meteor reactjs ecmascript-6


    【解决方案1】:

    AFAI 可以看到你应该从this.props 中获取currentUser 而不是this.data

    render() {
      var fullname = '';
      var currentUser = this.props.currentUser;
      if(currentUser && currentUser.profile) {
        fullname = `${currentUser.profile.firstname} ${currentUser.profile.lastname}`;
        // use fullname for something...
      }
      return;
    }
    

    【讨论】:

    • 哦,我的错。抱歉,在我在导航栏组件中使用 getMeteorData() 之前没有使用任何 mixin 功能,所以我使用了 this.data。感谢您的帮助。
    • 即使在执行 this.props.currentUser 之后我也无法定义。
    • @milan 那是因为Meteor.user() 返回undefined 但您没有发布那部分代码。您应该考虑使用相应的代码提出一个新问题。
    • 我已经发布了 Meteor.user(),它位于 ReactMeteorDataWrap 组件 getMeteorData() 中,并在 Navbar.jsx 中使用 this.props.getMeteor() 调用。
    • stackoverflow.com/questions/37494652/…。如果你能帮助我,我问了一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多