我遇到了一個非常奇怪但看似簡單的問題。
我確實有一個名為的物件vatRates,如下所示:
const vatRates = {
"AD": 0.00,
"CZ": 1.21,
"RO": 1.19,
"DE": 1.19,
"RS": 0.00,
"RU": 0.00,
"SE": 1.25,
"SI": 1.22,
"SK": 1.20,
"TR": 0.00,
"UA": 0.00,
"US": 0.00
}
countryCode我從我的 React中呼叫了一個常量Context, countryCode 有一個默認值“DE”,然后在背景關系初始化期間更改為“CZ”。
countryCode永遠不會為空或未定義。
在我的組件中,我想獲取物件countryCode中的值vatRates。
代碼應該很簡單吧?
console.log(vatRates[countryCode])
但它僅在countryCode具有默認值“DE”時才有效,即使物件上存在鍵“CZ”。
這是我得到的控制臺日志。我真的不知道為什么這個簡單的事情不起作用。

當我手動訪問這樣的物件時,它作業正常。
vatRates["CZ"]
這是一個顯示問題的代碼框
uj5u.com熱心網友回復:
與您的背景關系有關的一切都可以。問題是 API 的值中有一些空格。
只需vatRates[countryCode.trim()]在背景關系中使用甚至更好:
const fetchCountryCode = async () => {
const res = await fetch("https://get.geojs.io/v1/ip/country");
const countryCode = await res.text();
return countryCode.trim();
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460653.html
標籤:javascript 反应 细绳 目的 反应上下文
上一篇:'submit()'方法是否會阻止執行'submit'事件偵聽器?
下一篇:在頁面加載時顯示div
