无法读取属性'长度'在尝试获取对象时未定义

时间:2017-06-28 21:45:42

标签: javascript reactjs

我正在尝试将我的玩家JSX中的玩家数量渲染到我的应用程序,但是当我尝试使其工作时仍然获得Cannot read property 'length' of undefined。我不确定这里有什么不对,而且有点丢失。

我的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>
  )
}

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您需要将玩家道具传递给组件,如下所示:

<Stats players={players} />

此外,您可以在Stats组件中设置空检查,以处理未被传入的玩家。

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

答案 1 :(得分:1)

Stats不是一个组件,它是一个函数,因此您必须将其重写为React组件或实际使用它作为函数,即替换:

<Stats />

... with:

{Stats(this.props)}