簡體   English   中英

與Typescript反應:渲染來自`map`函數的組件

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

我下面有從json文件中獲取的data ,還導入了一個實用程序函數,該函數從對象Array中選取5個隨機實體,在這種情況下,該data數組具有30個實體。

我正在努力呈現存儲在unique的5個隨機jockies。 我是ES6語法的新手。 我怎樣才能使5位騎師unique 目前我正在

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

您應該將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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM