首页 > 解决方案 > 从 React 中的 Cookie 获取电话号码前缀

问题描述

我知道我们可以用这个方法得到一个国家的iso代码:

import Cookies from 'js-cookie';
const iso = Cookies.get('CK_ISO_CODE');
console.log(iso); // -> 'us'

有没有办法获取电话前缀?

例如,对于美国,它应该是 +1,对于 FR +33 等等。

标签: javascriptreactjscookiesisojs-cookie

解决方案


你会想要使用这个 npm 包:https ://www.npmjs.com/package/world-countries

首先,这是一个在片段中工作的示例。我们必须获取 JSON 文件,以便 eventListener 是异步的,但如果您使用 npm 包(下一个示例),它不必是异步的。

document.querySelector("#load-prefix").addEventListener("click", async () => {
  const world = await fetch(`https://cdn.jsdelivr.net/npm/world-countries@4.0.0/countries.json`).then(res => res.json())
  const iso = document.querySelector("#iso").value;
  const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
  const phonePrefixStart = country ? country.idd.root : "unknown";
  const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
  const phonePrefix = phonePrefixStart + phonePrefixEnd;
  document.querySelector("#output").innerText = phonePrefix;
});
<input placeholder="iso code" id="iso" />
<button id="load-prefix">Get Phone Prefix</button>
<p id="output"></p>

使用 npm 包,它看起来像这样。(此示例不起作用,因为 Stack Snippets 不包含模块捆绑器)

const world = require('world-countries')
// or
import world from "world-countries";

document.querySelector("#load-prefix").addEventListener("click", () => {
  const iso = document.querySelector("#iso").value;
  const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
  const phonePrefixStart = country ? country.idd.root : "unknown";
  const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
  const phonePrefix = phonePrefixStart + phonePrefixEnd;
  document.querySelector("#output").innerText = phonePrefix;
});
<input placeholder="iso code" id="iso" />
<button id="load-prefix">Get Phone Prefix</button>
<p id="output"></p>

所以回到你的问题,它看起来像这样:

import Cookies from 'js-cookie';
import world from "world-countries";
const iso = Cookies.get('CK_ISO_CODE');
console.log(iso); // -> 'us'
const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
const phonePrefixStart = country ? country.idd.root : "unknown";
const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
const phonePrefix = phonePrefixStart + phonePrefixEnd;
console.log(phonePrefix); // -> '+1'

推荐阅读