【问题标题】:A simple currency converter in React does not update when the currency is changedReact 中的一个简单货币转换器在货币更改时不会更新
【发布时间】:2023-02-12 16:10:23
【问题描述】:

我正在尝试在 React 中构建一个简单的货币转换器。但是,当我尝试从下拉列表中更改货币时,汇率不会更新。我想这将是从 API 获取速率的 useEffects 之一的问题。但是我迷路了。

这些是我在控制台中遇到的错误: “react-dom.development.js:86 警告:收到 value 属性的 NaN。如果这是预期的,请将该值转换为字符串。”和“VM586:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"

我的代码:

应用程序.js:

import './App.css';
import React, { useEffect, useState } from 'react';
import CurrencyRow from './CurrencyRow';

const BASE_URL = 'https://api.exchangerate.host/latest';

function App() {
  const [currencyOptions, setCurrencyOptions] = useState([]);
  const [fromCurrency, setFromCurrency] = useState();
  const [toCurrency, setToCurrency] = useState();
  const [exchangeRate, setExchangeRate] = useState();
  const [amount, setAmount] = useState(1);
  const [amountInFromCurrency, setAmountInFromCurrency] = useState(true);

  let toAmount;
  let fromAmount;

  if (amountInFromCurrency) {
    fromAmount = amount;
    toAmount = amount * exchangeRate;
  } else {
    toAmount = amount;
    fromAmount = amount / exchangeRate;
  }

  useEffect(() => {
    fetch(BASE_URL)
      .then((res) => res.json())
      .then((data) => {
        const firstCurrency = Object.keys(data.rates)[0];
        setCurrencyOptions([...Object.keys(data.rates)]);
        setFromCurrency(data.base);
        setToCurrency(firstCurrency);
        setExchangeRate(data.rates[firstCurrency]);
      });
  }, []);

  useEffect(() => {
    if (fromCurrency != null && toCurrency != null) {
      fetch(`$(BASE_URL)?base=${fromCurrency}&symbols=${toCurrency}`)
        .then((res) => res.json())
        .then((data) => setExchangeRate(data.rates[toCurrency]));
    }
  }, [fromCurrency, toCurrency]);

  function handleFromAmountChange(e) {
    setAmount(e.target.value);
    setAmountInFromCurrency(true);
  }

  function handleToAmountChange(e) {
    setAmount(e.target.value);
    setAmountInFromCurrency(false);
  }

  return (
    <>
      <h1>Convert currency</h1>
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={fromCurrency}
        onChangeCurrency={(e) => setFromCurrency(e.target.value)}
        onChangeAmount={handleFromAmountChange}
        amount={fromAmount}
      />
      <div className="equals">=</div>
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={toCurrency}
        onChangeCurrency={(e) => setToCurrency(e.target.value)}
        onChangeAmount={handleToAmountChange}
        amount={toAmount}
      />
    </>
  );
}

export default App;

货币行.jsx:

/* eslint react/prop-types: 0 */

import React from 'react';
import './App.css';

const BASE_URL = 'https://api.exchangerate.host/latest';

function CurrencyRow(props) {
  const {
    currencyOptions,
    selectedCurrency,
    onChangeCurrency,
    amount,
    onChangeAmount,
  } = props;

  return (
    <div>
      <input
        type="number"
        className="input"
        value={amount}
        onChange={onChangeAmount}
      />
      <select value={selectedCurrency} onChange={onChangeCurrency}>
        {currencyOptions.map((option) => (
          <option key={option} value={option}>
            {option}{' '}
          </option>
        ))}
      </select>
    </div>
  );
}

export default CurrencyRow;

任何帮助将不胜感激!非常感谢!

【问题讨论】:

  • 请检查您的 api 响应一次。我猜它没有给出预期的响应

标签: javascript reactjs json api


【解决方案1】:

我无法完全调试您的代码,但我认为问题会发生在 if 语句中的第二个 useEffect 中。

因为 fromCurrencytoCurrency 的初始值是 undefined 但你将它与 null 进行比较所以它无论如何都会获取,因为该值是 undefined 而不是 Null

所以我认为您需要将 if 语句更改为那样

if (!fromCurrency || !toCurrency) {
   // do fetch and the rest here.
}

这意味着除非您有两个值,否则您不会进行提取。不接受空字符串、undefined 或 null。

【讨论】:

    【解决方案2】:

    问题是当您使用 fromCurrency 和 toCurrency 调用 API 时。模板文字是错误的。将 BASE_URL 变量括在花括号中,而不是圆括号中。改成fetch(`${BASE_URL}?base=${fromCurrency}&amp;symbols=${toCurrency}`)

    查看此 Codesandbox 链接 https://codesandbox.io/s/cold-sky-us38d7?file=/src/App.js

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加更多详细信息,以帮助其他人了解这如何解决所提出的问题。你可以在in the help center找到更多关于如何写出好的答案的信息。
    猜你喜欢
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多