我已经创建了一个货币兑换应用程序.我的应用程序接受数字作为输入,运行良好.然而,当用户输入数字以外的内容或将输入字段留空时,我的应用程序不会执行任何操作.我希望它返回一个错误通知,说明需要提供一个数字.
这是我当前的代码,但它不起作用.它甚至不会在控制台上抛出错误,而是像提供了数字一样try 获取.
input.js:个
import React, { useState } from 'react';
const Input = ({ dropdown, onChange, label, symbols }) => {
const arrOfSymbols = Object.keys(symbols);
arrOfSymbols.sort();
const [error, setError] = useState('');
const handleInputChange = (e) => {
const inputValue = e.target.value;
console.log('Input Value:', inputValue);
// Check if the input is empty or not a number
if (inputValue.trim() === '' || isNaN(inputValue)) {
// Set the error state
setError('Please enter a valid number.');
console.log('Error:', 'Please enter a valid number.');
} else {
// If the input is valid, clear the error state
setError('');
// Proceed with the provided onChange callback
onChange(inputValue);
}
};
Input field on input.js:个
<input type="number" placeholder="Enter the number you want to convert" className="px-4 py-2 rounded-xl" onChange={handleInputChange} />
Fetching part of index.js:个
// FETCH
const convertCurrency = () => {
const options = {
method: "GET",
url: "http://localhost:3000/api/convert",
params: { convertFrom, convertTo, amount },
};
axios.request(options).then(function (response) {
const { data } = response;
setConvertedAmount((data.result));
setError(null); // Clear any previous errors
}).catch(function (error) {
console.error(error);
setError('An error occurred during conversion.'); // Set an error message
});
};
当我单击Convert按钮(触发上面的ConvertCurrency函数)时,当输入字段为空或非数字时,我的控制台抛出的内容:
获取http://localhost:3000/api/convert?convertFrom=ANG&;convertTo=ANG&;amount=