简体   繁体   中英

meteor + react “Uncaught TypeError: Cannot read property 'data' of undefined”

Im using Meteor + React and "this.props.thing.source" is a string for a mongodb _id.

The "findOne()" function is one of Meteor's. As you can see it works fine when I pass in the string of the ID itself, but I get an undefined error when passing in the variable, even though that variable renders out that same string.

In this code:

Thing = React.createClass({
  propTypes: {
    thing: React.PropTypes.object.isRequired
  },
  render() {
    return (
      <ul>
        <li>Display: {Things.findOne(this.props.thing.source).data}</li>
        <li>Display: {Things.findOne("emq6M4WbJeRvkA6Q3").data}</li>
        <li>Source: {this.props.thing.source}</li>
      </ul>
    );
  }
});

This does NOT work:

  • Display: {Things.findOne(this.props.thing.source).data}
  • This works:

  • Display: {Things.findOne("emq6M4WbJeRvkA6Q3").data}
  • And this correctly renders "emq6M4WbJeRvkA6Q3":

  • Source: {this.props.thing.source}
  • The ERROR I am getting:

    "Uncaught TypeError: Cannot read property 'data' of undefined"

    You're getting the error because of whatever Things.findOne() returns is undefined .

    You say that calling above function with the this.props.thing.source does not work, which is wrong but since you're not mentioning how the rendering of your Thing component takes place your best bet to find the error is the way you're passing the prop this.props.thing.source /what you're passing to your component.

    I made a quick copy-paste example that illustrates and also made your component work in a JSFiddle

    var Things = {
        findOne: function (thingSource) {
            if (thingSource) {
                return {
                    data: 'It did work!'
                };
            }
            return undefined;
        }
    }
    
    var Thing = React.createClass({
        propTypes: {
            thing: React.PropTypes.object.isRequired
        },
        render: function() {
            return <div>Hello {Things.findOne(this.props.thing.source).data}</div>;
        }
    });
    
    React.render(<Hello thing={{source: true}} />, document.body);
    

    A working example with your exact component can be found here

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM