在使用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);
也许用户组件的渲染方法在电子邮件解决之前和解析后第二次被调用两次。尝试在你的用户组件的渲染方法中放置一个console.log(this.props) – Swapnil
到目前为止如何?这个.props.user的日志值是多少?大多数时候可能是电子邮件属性尚未发送到客户端。 – collision
@Swapnil按照建议添加'console.log',我得到'Object {users:Array [0]}'后面跟着'Object {users:Array [1]}' – Nyxynyx