javascript - 从 API 随机生成国家/地区名称

标签 javascript arrays reactjs random react-hooks

我正在使用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/

相关文章:

javascript - 从 Javascript 修改框架滚动

javascript - ReactJS 如何将当前列表项嵌套数组渲染到选择中

javascript - 文本组件给定不同组件中的行数

javascript - minko 从 dom 获取对象

javascript - 瑞典语字符问题

javascript - iphone safari 的隐藏 iframe 问题

c++ - 访问无限数组元素?

arrays - 使用Hive在数组中创建结构

java - 有没有办法在 Java 中将 0x80-0xFF 范围表示为单个字节?

javascript - TypeError : Object(. ..) 不是使用 useHistory() 钩子(Hook)时的函数