React Components, MongoDB and passing a Key - TypeError: Cannot read property '_id' of undefined

问题: So I'm trying to pass a field from a MongoDB into a React Component as such: import React from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from 'meteor/...

问题:

So I'm trying to pass a field from a MongoDB into a React Component as such:

import React from 'react';
import ReactDOM from 'react-dom';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Players } from './../imports/api/players';
import TitleBar from './../imports/UI/TitleBar';
import AddPlayer from './../imports/UI/AddPlayer';
import Player from './../imports/UI/Player';

const renderPlayers = (playersList) => {
    return playersList.map((player) => {
        return <Player key={player._id} />;
    });
};

But the component isn't able to read the passed in player._id value.

import React from 'react';
import { Players } from './../api/players';

export default class Player extends React.Component {
    render() {
        return (
            <p key={this.props.player._id}>
                {this.props.player.name} has {this.props.player.score} point(s).
                <button onClick={() => {Players.update(this.props.player._id, { $inc: { score: 1 } });}}>+1</button>
                <button onClick={() => {Players.update(this.props.player._id, { $inc: { score: -1 } });}}>-1</button>
                <button onClick={() => Players.remove(this.props.player._id)}>x</button>
            </p>
        );
    }
}

Functionality wise - the code works as intended - just not as a component here because player._id isn't able to be passed in. How do I go about passing the player._id field in properly?

Error: TypeError: Cannot read property '_id' of undefined

I thought it might be because there was no data entries in the DB - but I made sure to make a few beforehand and test that, didn't work unfortunately.


回答1:

In order to use _id or fields of the player object in the child component, you should pass a player object as props to child component from the Parent component. Check the modified code below

const renderPlayers = (playersList) => {
return playersList.map((player) => {
    return <Player key={player._id} player={player} />;
  });
}

then your child component will work fine.

  • 发表于 2018-12-28 15:50
  • 阅读 ( 192 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除