我正在使用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>
)
}
任何帮助将不胜感激!谢谢!
最佳答案
countryName
是一个函数,但您将其用作数组。所以你需要在设置数据时映射你的响应,然后你可以直接使用。尝试下面的代码
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(countryName(result))
console.log(result)
})
}, [])
const countryName = country => {
return country.map(d => d.name)
}
return (
<Card>
<Card.Body>{name}</Card.Body>
<Button
onClick={() =>
setCount(country[Math.floor(Math.random() * country.length)])
}
>
Click me
</Button>
</Card>
)
}
关于javascript - 从 API 随机生成国家/地区名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68214229/