简体   繁体   English

与Typescript反应:渲染来自`map`函数的组件

[英]React with Typescript: Render components from `map` function

I have below data that I get from a json file and also import a utility function that picks out 5 random entities from an object Array in this case data array which has 30 entities. 我下面有从json文件中获取的data ,还导入了一个实用程序函数,该函数从对象Array中选取5个随机实体,在这种情况下,该data数组具有30个实体。

I'm struggling to render the 5 random jockies that are stored in unique . 我正在努力呈现存储在unique的5个随机jockies。 I'm fairly new to the ES6 syntax. 我是ES6语法的新手。 How can I render the 5 jockeys from unique ? 我怎样才能使5位骑师unique Currently I'm getting 目前我正在

TypeError: Cannot read property 'avatar_url' of undefined 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> ) } } 

Definition of getUniqueJockeys 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; }; 

You should change the definition of getUniqueJockeys to be more generic. 您应该将getUniqueJockeys的定义更改为更通用。 If data is of type JockeyArray[] this should work (and you can use it for any values not just JockeyArray): 如果数据的类型为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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM