流星反应错误:无法读取属性'0'的未定义

[英]Meteor React Error: Cannot read property '0' of undefined


On a very simple Meteor app using React, there is a table that list out all the registered users from the Meteor.users collection.

在一个使用React的非常简单的流星应用程序中,有一个表格列出了所有流星的注册用户。用户收藏。

However when trying to display the email address of each user, the browser JS console is throwing the following error, although the email address is correctly rendered on the HTML page.

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

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

Why is this error happening?

为什么会发生这种错误?

/imports/ui/User.jsx

/ / 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

/ / 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);

1 个解决方案

#1


2  

Well it would seem this.props.user.emails is undefined. are you sure this is the correct key you are looking for?

看起来是这样的。提案。用户。电子邮件是未定义的。你确定这是你要找的正确的钥匙吗?

ways to fix this.

解决这个问题的方法。

pull in a library like lodash (it will change your life)

像lodash一样去图书馆(它会改变你的生活)

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

if you dont want to pull in something like lodash then check to see if the value is there..

如果你不想拖拽lodash之类的东西,那就检查一下它是否有这个值。

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/12/17/2b17cb34886a484776d4582181358920.html



 
  © 2014-2022 ITdaan.com 联系我们: