当我在useState()钩子中使用totalQuantity时,它返回undefined。但是如果我在useState()钩子中赋值totalQuantity = 100, totalQuantity = 200等,它就会显示数字。那么为什么useState(totalQuantity)返回未定义每当我分配totalQuantity的选项链接值作为初始计数?下面是代码:
const inventories = useInventory();
const { inventoryId } = useParams();
const selectedInventory = inventories.find(
(inventory) => inventory._id === inventoryId
);
const totalQuantity = selectedInventory?.quantity;
console.log(totalQuantity);
const [carQuantity, setCarQuantity] = useState(totalQuantity);
const quantityDecreaser = () => {
if (carQuantity > 0) {
setCarQuantity(carQuantity - 1);
const remainingQuantity = carQuantity - 1;
const data = { remainingQuantity };
fetch(`http://localhost:5000/inventories/${inventoryId}`, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
console.log(result);
});
}
};```
似乎你的selectedInventory返回undefined和
const totalQuantity = selectedInventory?.quantity;
这可能是由错误或不存在的inventoryId引起的。
检查selectedInventory是否有正确的数据,您也可以在这里使用默认值:
const [carQuantity, setCarQuantity] = useState(totalQuantity || defaultValue);
可能您的find方法返回undefined,因此状态为undefined
const get = (data) => {
const inventoryId = 8;
const selectedInventory = data.find(
inventory => inventory.id === inventoryId
);
return selectedInventory;
}
const totalQuantity = get([{id: 4,quantity:888 }, {id: 8, quantity:88 }, {id: 9, quantity:787}]);
const [carQuantity, setCarQuantity] = React.useState(totalQuantity);
console.log(carQuantity);
这可能是类型问题,因为您正在使用===检查是否相等,如果您的库存。_id是一个数字,因为useParams钩子将返回一个字符串。
使用双等号检查值仅为inventory._id == inventoryId
或
将inventoryId解析为带有加号的数字,例如inventory._id === +inventoryId
我使用useEffect()修复了它。可能setCarQuantity()没有立即设置值,在使用useEffect()之后,它会侦听状态变化。
const [carQuantity, setCarQuantity] = useState(totalQuantity);
useEffect(() => {
setCarQuantity(totalQuantity);
}, [totalQuantity]);