【问题标题】:Randomly generate country name from an API从 API 随机生成国家名称
【发布时间】: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


    【解决方案1】:

    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>
        )
    }
    

    【讨论】:

    • 谢谢!!如果我想访问数组中的其他对象怎么办?我可以在countryName 函数中映射超过 1 个对象吗? @尼尔
    • 不需要。您可以像这样添加相同的地图功能return country.map(d =&gt; {d.name, d.anotherObject})
    • 谢谢!我这样做了:country.map(d =&gt; ({name: d.name, population: d.population}))@Neel
    【解决方案2】:

    因为所有数据都以数组中的对象的形式出现。您可以做的不是尝试生成随机国家名称,而是生成随机数并传递它。因此,您将在按钮单击时获得随机国家。 在这里稍作修正。

    const [countries, setCountries] = useState([]);
    const [randomCountry, setRandomCountry] = useState(0)
    
    <Button onClick={() => setRandomCountry(Math.floor(Math.random() * countries.length))}> // this will just set the number for random country. pass randomCountry to useEffect as dependency array or you can use it some way in countries.map()
         Click me
    </Button>
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2019-04-14
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多