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

Arrays 如何使用React钩子从数组中选择随机对象?,arrays,reactjs,random,react-hooks,Arrays,Reactjs,Random,React Hooks,我不知道为什么我的功能不起作用。我不想显示数组中的随机城市?但若我点击按钮,然后显示给我 错误-: AppHooks.js:15 Uncaught TypeError: Cannot read property 'length' of undefined.` 我做错了什么 import React, {useState} from 'react'; export default function AppHooks () { const [cities, setCities] =

我不知道为什么我的功能不起作用。我不想显示数组中的随机城市?但若我点击按钮,然后显示给我

错误-:

AppHooks.js:15 Uncaught 
TypeError: Cannot read property 'length' of undefined.`
我做错了什么

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>

    )
}
import React,{useState}来自“React”;
导出默认函数AppHooks(){
const[城市,集合城市]=useState([
{
城市名称:“克拉科夫”
},
{
城市名称:“基尔切”
}
])
功能随机城市(e,城市){
设len=cities.length;
//设randCiti=cities[Math.floor(Math.random()*cities.length)];
setCities(cities[Math.floor(Math.random()*len)]);
回归城市
}
让citi=cities.map((cit,i)=>{
返回(
{cit.nameCity}
)
}
)
console.log(城市[0]);
返回(
{citi}
改变
)
}

onClick处理程序只给方法一个参数-事件。 所以你们的城市在这里没有定义:

let len = cities.length;
如果要通过onClick传递另一个参数,应使用箭头功能:

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

如果你想从你的数组中随机选择一个城市,我会设计不同的应用程序,只需设置要从中选择的索引

此外,如果您使用的是fat arrow函数,则无需将城市传递给click事件处理程序。我给你举了一个小例子

import React, { useState } from "react";
import ReactDOM from "react-dom";

function AppHooks() {
  const cities = [
    {
      nameCity: "Kraków"
    },
    {
      nameCity: "Kielce"
    }
  ];

  const [activeCity, setActiveCity] = useState(0);

  const randomCities = e => {
    const len = cities.length;
    setActiveCity(Math.floor(Math.random() * len));
  };

  return (
    <>
      <div>{cities[activeCity].nameCity}</div>
      <button onClick={randomCities}> Change</button>
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<AppHooks />, rootElement);
import React,{useState}来自“React”;
从“react dom”导入react dom;
函数AppHooks(){
康斯特城市=[
{
城市名称:“克拉科夫”
},
{
城市名称:“基尔切”
}
];
const[activeCity,setActiveCity]=useState(0);
常数随机数=e=>{
const len=cities.length;
setActiveCity(Math.floor(Math.random()*len));
};
返回(
{城市[activeCity].nameCity}
改变
);
}
const rootElement=document.getElementById(“根”);

ReactDOM.render(

谢谢您的答案有用谢谢您的答案有用。-->这是我的解决方案。现在我必须使子组件继承相同的:-)