与Typescript反应:从`map`函数渲染组件

时间:2018-02-22 18:58:56

标签: javascript reactjs typescript

我从json文件获得data以下,并且还导入了一个实用程序函数,该函数从一个对象数组中挑选出5个随机实体,在这种情况下data数组有30个实体。

我正在努力渲染存储在unique中的5个随机jockies。我是ES6语法的新手。如何从unique渲染5个骑师?目前我正在

  

TypeError:无法读取未定义的属性“avatar_url”

import * as React from 'react';
import { Jockey } from '../Jockey';
const data: JockeyArray[] = require('../../team.json');
import { getUniqueJockeys } from '../../utils/uniqueUtil';

interface JockeyArray {
    id: number;
    login: string;
    avatar_url: string;
}

interface State {
    nextRacers: string[];
    jockeys: JockeyArray[];
}

export class Race extends React.Component<Props, State> { 
    constructor(props: Props) {
        super(props);
        this.state = {
            jockeys: data as JockeyArray[], 
            nextRacers: [],
        };
    }

    render() {
        
        if (this.props.startRandom) { // random selection
            
            // returns data array as 5 unique entities
            const unique = getUniqueJockeys(data);
            console.log(unique);//I can see my 5 randoms generated.
        
        return (
          <div>
            { unique.map((racer, index) => (       
                        // ??
                   <Jockey avatar={racer[index].avatar_url} />
              ))}
          </div>
        )
    }

}

getUniqueJockeys

的定义

// Selecting 5 unique random jockeys
export const getUniqueJockeys = (anyArray: Array<object>) => {
    let uniqueArray = [];
    while (uniqueArray.length < 5) {
        const unique = Math.floor(Math.random() * anyArray.length);
        if (uniqueArray.indexOf(anyArray[unique]) > -1) {
            continue;
        }
        uniqueArray.push(anyArray[unique]);
    }
    return uniqueArray;
};

1 个答案:

答案 0 :(得分:2)

您应该将getUniqueJockeys的定义更改为更通用。如果数据类型为JockeyArray[],那么这应该可行(并且您可以将它用于任何值而不仅仅是JockeyArray):

export const getUniqueJockeys = <T>(anyArray: Array<T>) => {
    let uniqueArray: T[] = [];
    while (uniqueArray.length < 5) {
        const unique = Math.floor(Math.random() * anyArray.length);
        if (uniqueArray.indexOf(anyArray[unique]) > -1) {
            continue;
        }
        uniqueArray.push(anyArray[unique]);
    }
    return uniqueArray;
};