gpt4 book ai didi

javascript - React 组件、MongoDB 和传递 key - TypeError : Cannot read property '_id' of undefined

转载 作者:行者123 更新时间:2023-11-30 14:13:39 28 4
gpt4 key购买 nike

所以我试图将一个字段从 MongoDB 传递到 React 组件中:

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

但是组件无法读取传入的 player._id 值。

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

功能方面 - 代码按预期工作 - 只是不是这里的一个组件,因为无法传入 player._id。我该如何正确传递 player._id 字段?

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

我认为这可能是因为数据库中没有数据条目 - 但我确保事先做了一些并进行了测试,不幸的是没有用。

最佳答案

为了在子组件中使用玩家对象的 _id 或字段,您应该将玩家对象作为 Prop 从父组件传递给子组件。检查下面修改后的代码

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

然后您的子组件将正常工作。

关于javascript - React 组件、MongoDB 和传递 key - TypeError : Cannot read property '_id' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53939589/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com