【发布时间】:2021-06-10 18:03:06
【问题描述】:
我有一个对象,我想检查它的字段是否为空,然后我想发送一个请求。这是我的代码:
const [newProduct, setNewProduct] = useState({
name: null,
cost: null,
size: null,
color: null,
material: null,
discount: null,
description: null,
category: null
});
const addNewProduct = () => {
if(newProduct.name && newProduct.cost && newProduct.size && newProduct.color && newProduct.material && newProduct.discount && newProduct.description && newProduct.category) {
let productFormData = new FormData();
productFormData.append('productInfo', JSON.stringify(newProduct));
productFormData.append('productImages', images.imageFiles);
const addUrl = "http://localhost:8080/cpnl/addproduct";
axios({
method: "POST",
url: addUrl,
data: productFormData,
headers: { "Content-Type": "multipart/form-data" }
})
.then((response) => {
console.log(response.data.msg);
})
.catch((response) => {
console.error(response);
});
}
};
有没有办法让 if 语句更短? 我需要定义所有字段来修改它们吗?
【问题讨论】:
标签: javascript json object if-statement