在 React useEffect 中获取 URI 的模板文字中插入参数

问题描述 投票:0回答:1

利用 .then 并插入 '...${currency}.json' 参数的 fetch uri 可以正确运行,没有错误:

useEffect(() => {
   fetch(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${currency}.json`)
      .then((res) => res.json())
      .then((res) => setData(res[currency]))
}, [currency])

使用异步等待并插入 '...${currency}.json' 参数的 fetch uri 会在参数插入 '...${currency}.json' 时出现语法错误:

const useCurrencyInfo2 = (currency) => {
   const [data, setData] = useState({});
   const [isError, setIsError] = useState(false);

   useEffect(() => {
      const fetchCurrency = async () => {
         try {
            const resp = await fetch(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${currency}.json`)

            if (!resp.ok) {
               setIsError(true)
               return
            }
            const json = await resp.json()
            setData(json[currency])

         } catch (error) {
            setIsError(true)
         }
      }
      fetchCurrency();
   }, [currency])
  
   return data
}
reactjs fetch-api template-literals
1个回答
0
投票

在第二个片段中,在效果中定义变量

currency
,它会隐藏钩子参数中的原始
currency

const currency = await resp.json()

现在,浏览器在执行 fetch 时知道当前范围内会有变量

currency
,但它还没有定义。因此,当您尝试尚未定义的变量时,它会引发错误。要解决此问题,您需要对响应的 json 使用不同的变量名称:

const json = await resp.json()
setData(json[currency])
© www.soinside.com 2019 - 2024. All rights reserved.