【问题标题】:How to get cities list of each state of United States in React如何在 React 中获取美国各州的城市列表
【发布时间】:2021-02-09 11:12:10
【问题描述】:

美国有 51 个州。 每个州都有很多城市。 我想获取每个州的城市列表。 所以我只是尝试如下。

使用过的库:

npm install country-state-city
npm install usa-states
import { UsaStates } from 'usa-states';
import csc from 'country-state-city';

const usStates = new UsaStates();
const states = usStates.states.map((state) => state.name);
const cities = csc.getCitiesOfCountry(states[0]);

但是变量cities没有结果。

【问题讨论】:

  • “美国有 51 个州” - 你甚至没有正确理解地缘政治的基本事实这一事实并不能让我对你的其余部分充满信心能力...
  • 请不要粘贴可以用文字代替的图片。 meta.stackoverflow.com/questions/285551/…
  • But no results 是什么意思?你不要console.log它,你没有报告任何错误。此外,您可以通过发布库文档来帮助您的助手(我们),我们(和您)可以在其中阅读其 API 文档。
  • csc 来自哪里?
  • @Dai Politics of USA != geopolitics.

标签: node.js reactjs npm


【解决方案1】:

您可能需要使用csc.getCitiesOfState(countryCode, stateCode) 而不是csc.getCitiesOfCountry。另外,你不需要usa-states 包:

const countryCode = 'US';
const country = csc.getCountryByCode(countryCode);
const states = csc.getStatesOfCountry(country.isoCode);
const citiesFromFirstState = csc.getCitiesOfState(countryCode, states[0].isoCode);

console.log("Cities:", {
  state: states[0],
  cities: citiesFromFirstState,
});

注意:看看它是test suite

【讨论】:

    【解决方案2】:

    这是正确答案。

    首先,请安装正确的模块。

    npm install country-state-city
    

    完整代码:

    import csc from 'country-state-city';
    
    const countryCode = 'US';
    const country = csc.getCountryByCode(countryCode);
    const states = csc.getStatesOfCountry(country.isoCode);
    states.forEach((state) => {
        cities_of_state = csc.getCitiesOfState(countryCode, state.isoCode)
        console.log(state, ":", cities_of_state)
    })
    
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 2022-12-13
      • 2013-02-08
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多