2016-12-17 62 views
2

在使用React的非常简单的Meteor应用程序中,有一张表列出了Meteor.users集合中的所有注册用户。流星反应错误:无法读取未定义的属性'0'

但是,当试图显示每个用户的电子邮件地址时,尽管电子邮件地址在HTML页面上正确呈现,但浏览器JS控制台仍在抛出以下错误。

Exception from Tracker recompute function: 
TypeError: Cannot read property '0' of undefined 
    at Users.render (User.jsx:8) 

为什么这个错误发生?

/imports/ui/User.jsx

import React, { Component } from 'react'; 

export default class Users extends Component { 
    render() { 
     return (
      <tr> 
       <td>{ this.props.user._id}</td> 
       <td>{ this.props.user.emails[0].address }</td> // this is line 8 
      </tr> 
     ) 
    } 
} 

/imports/ui/App.jsx

import React, { Component, PropTypes } from 'react'; 
import { createContainer } from 'meteor/react-meteor-data'; 

import User from './User'; 

export class App extends Component { 

    renderUsers() { 
     return this.props.users.map((user) => (
      <User key={user._id} user={user} /> 
     )); 
    } 


    render() { 
     return (
      <div> 
       <h1>Users</h1> 

       <table> 
        <tbody> 
         <tr> 
          <td>ID</td> 
          <td>Email</td> 
         </tr> 
         { this.renderUsers() } 
        </tbody> 
       </table> 
      </div> 
     ) 
    } 
} 

App.propTypes = { 
    users: PropTypes.array.isRequired 
} 

export default createContainer(() => { 
    return { 
     users: Meteor.users.find().fetch() 
    } 
}, App); 
+0

也许用户组件的渲染方法在电子邮件解决之前和解析后第二次被调用两次。尝试在你的用户组件的渲染方法中放置一个console.log(this.props) – Swapnil

+0

到目前为止如何?这个.props.user的日志值是多少?大多数时候可能是电子邮件属性尚未发送到客户端。 – collision

+0

@Swapnil按照建议添加'console.log',我得到'Object {users:Array [0]}'后面跟着'Object {users:Array [1]}' – Nyxynyx

回答

2

那么它似乎this.props.user.emails是不确定的。你确定这是你正在寻找的正确钥匙吗?

解决这个问题的方法。

拉像lodash库(它会改变你的生活)

import _ from 'lodash'; 
.... 
<td>{_.get(this.props, 'users.emails[0].address', 'UNKNOWN ADDRESS')}</td> 

,如果你不想在像lodash拉然后检查值是否有..

var address = 'UNKNOWN ADDRESS'; 
if(this.props.users.emails && this.props.users.emails.length > 0) { 
    address = this.props.users.emails[0].address; 
} 
+0

它是正确的键,当第一次调用renderUsers()函数时未定义,然后在第二次再次调用时定义。 – Nyxynyx

+0

作为使用lodash的'_.get'的替代方法,有没有办法让React只在检索到集合时才渲染组件? – Nyxynyx

+0

@Nyxynyx是啊,如果你想有条件地呈现用户的基础上,如果他们的信息已经加载或没有,然后只是在检查,看看用户的电子邮件是否存在..如果它不是然后不呈现该项目 –