gpt4 book ai didi

javascript - 尝试获取对象数量时无法读取未定义的属性 'length'

转载 作者:行者123 更新时间:2023-11-28 14:50:09 25 4
gpt4 key购买 nike

我正在尝试将玩家数量从玩家 JSX 渲染到我的应用程序,但当我尝试使其工作时,不断出现无法读取未定义的属性“长度”。我不确定这里出了什么问题,我有点迷失了。

我的players.js(为简洁起见缩写)是这样的:

    const players = [
{
name: "Scott",
score: 10,
id: 1,
},
{
name: "Justin",
score: 40,
id: 2,
},
];

export default players;

在我的 Container.js 中,我有:

import React, { Component } from 'react';
import update from 'react/lib/update';
import Counter from './Counter';
import Titles from '../../../scaffold/titles';
import styled from 'styled-components';
import players from './players';
import {ContainLeft} from '../../../helper/comps';

const ProjectTitle = styled.h1`
color: white;
margin-top: 1em;
margin-bottom: 0;
`

const Copy = styled.p`
color: #F86195;
margin-top: 0;
margin-bottom: 2em;
`

function Stats(props) {
const totalPlayers = props.players.length;
return (
<div>
<p>{totalPlayers}</p>
</div>
)
}

class Container extends Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
countInfo: []
}
}

moveCard(dragIndex, hoverIndex) {
const { cards } = this.state;
const dragCard = cards[dragIndex];

this.setState(update(this.state, {
cards: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard],
],
},
}));
}

render() {
const listPlayers = players.map(player =>
<Counter
key={player.id}
player={player}
/>
);
return(
<ContainLeft style={{alignItems: 'center'}}>
<Stats />
<ProjectTitle>Score Keeper</ProjectTitle>
<Copy>A sortable list of players that with adjustable scores. Warning, don't go negative!</Copy>
<div>
{listPlayers}
</div>
</ContainLeft>
)
}
}

export default Container

我希望渲染玩家总数(在本例中应该只有 2 个玩家)的方法不起作用,而且我知道我的语法中的某些内容非常不正确。

我知道引发错误的部分是:

function Stats(props) {
const totalPlayers = props.players.length;
return (
<div>
<p>{totalPlayers}</p>
</div>
)
}

有什么想法吗?

最佳答案

您需要将玩家 Prop 传递到组件中,如下所示:

<Stats players={players} />

此外,您可以在统计组件中放置一个空检查来处理未传入的玩家。

const totalPlayers = props.players ? props.players.length : 0;

关于javascript - 尝试获取对象数量时无法读取未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813059/

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