【发布时间】:2021-07-01 17:00:27
【问题描述】:
我正在使用https://restcountries.eu/rest/v2/all 获取所有国家/地区的名称。
我正在尝试通过点击生成一个随机的国家/地区名称。我已经通过对象数组进行映射以获取国家/地区的名称,但 onClick 不起作用。
const WorldCard = () => {
const [country, setCountry] = useState([])
const [name, setCount] = useState(0)
useEffect(() => {
fetch('https://restcountries.eu/rest/v2/all')
.then(res => res.json())
.then(result => {
setCountry(result)
console.log(result)
})
}, [])
const countryName = country => {
return country.map(d => d.name)
}
return (
<Card>
<Card.Body>{name}</Card.Body>
<Button
onClick={() =>
setCount(countryName[Math.floor(Math.random() * countryName.length)])
}
>
Click me
</Button>
</Card>
)
}
任何帮助将不胜感激!谢谢!
【问题讨论】:
标签: javascript arrays reactjs random react-hooks