如何使用React Hooks从数组中选择随机对象?

时间:2019-04-09 12:00:35

标签: arrays reactjs random react-hooks

我不知道为什么我的功能不起作用。我不会显示数组中的随机引用吗?但是,如果我单击按钮,然后显示错误“ AppHooks.js:15 Uncaught TypeError:无法读取未定义的属性'length'”。

我做错了什么?

import React, {useState} from 'react';


export default function AppHooks () {
    const [cities, setCities] = useState([
        {
            nameCity: 'Kraków'
        },
        {
            nameCity: "Kielce"
        }
    ])

    function randomCities (e, cities) {
        let len = cities.length;
        // let randCiti = cities[Math.floor(Math.random() * cities.length)];
        setCities(cities[Math.floor(Math.random() * len)]);
        return cities
    }
    let citi = cities.map((cit, i) => {
        return(
        <div key={i}>
            {cit.nameCity}
        </div>)
        }
    )

    console.log(cities[0]);
    return(
        <div>
            {citi}
            <button onClick={randomCities}> Change</button>
        </div>

    )
}

2 个答案:

答案 0 :(得分:2)

您的onClick处理程序仅向您的方法提供一个参数-事件。 因此,您的城市在这里未定义:

let len = cities.length;

如果要通过onClick传递另一个参数,则应使用箭头功能:

onClick={event => randomCities(event, cities)}

答案 1 :(得分:1)

如果您想从阵列中获得一个随机城市,我会设计与众不同的应用程序,只需设置要选择的索引即可。

此外,如果您使用粗箭头功能,则无需将城市传递给click事件处理程序。我为您创建了一个小示例。

using (var browser = new System.Windows.Forms.WebBrowser())
{
     browser.DocumentCompleted += delegate
     {
         using (var pic = new Bitmap(browser.Width, browser.Height))
         {
             browser.DrawToBitmap(pic, new Rectangle(0, 0, pic.Width, pic.Height));
             pic.Save(imagePath);
         }
     };

     browser.Navigate(Server.MapPath("~") + htmlPath); //a file or a url
     browser.ScrollBarsEnabled = false;

     while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
     {
         System.Windows.Forms.Application.DoEvents();
     }
}

CodeSandbox - Example