我有一个 React 代码片段,其中使用了以下四个 JavaScript 变量:
total
totalTaxFree
addItemToCart
updateItemFromCart
removeItemFromCart
我想在下面的 React 代码中添加验证。验证应确保当用户输入的金额小于 25 美元或大于 1000 美元时,不应将其添加到购物车。
const total = useMemo(() => {
// calculation logic here
}, []);
const totalTaxFree = useMemo(() => {
// calculation logic here
}, []);
const addItemToCart = useCallback((item) => {
// Add item to cart logic here
}, []);
const updateItemFromCart = useCallback((item) => {
// update logic here
}, []);
const removeItemFromCart = useCallback((itemId) => {
// remove logic here
}, []);
这是我尝试过的,但我不知道需要在哪里放置以下代码
if (item.amount < 25 || item.amount > 1000)
{
console.log("Invalid amount. It should be between $25 and $1000.");
return;
}
你可以像这段代码一样进行验证,尝试这样
import React, { useCallback, useMemo, useState } from 'react';
const CartComponent = () => {
const [items, setItems] = useState([]);
const addItemToCart = useCallback((item) => {
if (item.amount < 25 || item.amount > 1000) {
console.log("Invalid amount. It should be between $25 and $1000.");
return;
}
setItems(prevItems => [...prevItems, item]);
console.log("Item added to cart", item);
}, []);
const updateItemFromCart = useCallback((item) => {
if (item.amount < 25 || item.amount > 1000) {
console.log("Invalid amount. It should be between $25 and $1000.");
return;
}
setItems(prevItems => prevItems.map(i => i.id === item.id ? item : i));
console.log("Item updated in cart", item);
}, []);
return (
<div>
<p>Total: {total}</p>
<p>Total Tax Free: {totalTaxFree}</p>
<button onClick={() => addItemToCart({id: 1, amount: 50, taxFree: false})}>Add Item</button>
<button onClick={() => updateItemFromCart({id: 1, amount: 30, taxFree: true})}>Update Item</button>
</div>
);
};
export default CartComponent;