object.key,用于将对象用作映射上的数组,而不是将参数作为道具传递给React组件



codesandbox的链接-https://codesandbox.io/s/productupload-form-krovj?fontsize=14&隐藏导航=1&主题=深色

在productupload react组件中,我使用product_specsuseState钩子,它是数组,但由于其他useStates是对象,只有product_specs useState是数组,因此很难在此实现handleChange事件处理程序。因此,我将product_specs改为object,而不是数组。由于我不能在对象上使用map方法,我使用了object.key,但现在的问题是,我不能在map中使用名为item的参数,并将其传递给react组件。它给出的错误是-无法读取未定义的属性长度。因为我使用item.specification作为组件的道具。有人能帮我解决这个问题吗。注意,我不能对组件代码进行任何更改,因为许多其他组件都依赖于它

productupload和forminput组件的代码如下所示。

import React, { useState } from "react";
import FormInput from "../Forminput/forminput";
import CustomButton from "../Custombutton/custombutton";
import axios from "axios";
const ProductUpload = () => {
const [sub_category, setSub_category] = useState("");
const [product_name, setProduct_name] = useState("");
const [product_image, setProduct_image] = useState("");
const [product_specs, setProduct_specs] = useState([
{
specification: "",
specvalue: "",
},
]);
//note VIMP to add square bracket for array
const imageSelectedHandler = (event) => {
setProduct_image({ product_image: event.target.files[0] });
};
// const imageUploadHandler = () => {
//   const fd = new FormData();
//   fd.append("product_image", product_image, product_image.name); //.name is Imp as name is property of file
// };
const handleChange = (e) => {
const { name, value } = e.target;
setSub_category({ ...sub_category, [name]: value });
setProduct_name({ ...product_name, [name]: value });
setProduct_specs({ ...product_specs, [name]: value });
// const p_specs = [...product_specs];
// p_specs[i][name] = value;
// setProduct_specs(p_specs); //This is 100% right.
console.log(product_specs);
};
//to add extra input field
const addClick = () => {
// setProduct_specs([...product_specs, { specification: "", specvalue: "" }]); //this is 100% right
//also 100% correct alternative to above line
const p_specs = [...product_specs];
p_specs.push({ specification: "", specvalue: "" });
setProduct_specs(p_specs);
};
//to remove extra input field
const removeClick = (i) => {
const p_specs = [...product_specs];
p_specs.splice(i, 1);
setProduct_specs(p_specs);
};
const handleSubmit = async (event) => {
event.preventDefault();
const newProduct = {
sub_category,
product_name,
product_image,
product_specs,
};
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(newProduct);
const res = await axios.post("/api/product", body, config);
console.log(res.data);
} catch (error) {
console.error(error.response.data);
}
};
const createUI = () => {
return Object.keys(product_specs).map((item, i) => {
return (
<div key={i} className="inputgroup">
<FormInput
type="text"
name="specification"
handleChange={(e) => handleChange(e, i)}
value={item.specification}
label="specification"
required
customwidth="300px"
></FormInput>
<FormInput
type="text"
name="specvalue"
handleChange={(e) => handleChange(e, i)}
value={item.specvalue}
label="specification values seperated by quomas"
required
></FormInput>
<CustomButton
onClick={() => removeClick(i)}
type="button"
value="remove"
style={{ margin: "12px" }}
>
Remove
</CustomButton>
</div>
);
});
};
return (
<div className="container">
<form
action="/upload"
method="post"
className="form"
onSubmit={handleSubmit}
encType="multipart/form-data"
>
<h3 style={{ color: "roboto, sans-serif" }}>
Add new product to the database
</h3>
<div
style={{
display: "flex",
height: "200px",
width: "200px",
border: "2px solid #DADCE0",
borderRadius: "6px",
position: "relative",
}}
>
<input
// style={{ display: "none" }}
type="file"
accept="image/*"
onChange={imageSelectedHandler}
multiple={false}
name="product_image"
/>
{/* <CustomButton >
Select Image
</CustomButton>
<CustomButton
//  onClick={imageUploadHandler}
>
Upload
</CustomButton> */}
{/*as per brad- type = "submit" value="submit"  this should not be used, file should upload with the form submit */}
<div>
<img
style={{
width: "100%",
height: "100%",
}}
alt="#"
/>
</div>
</div>
<FormInput
type="text"
name="sub_category"
handleChange={handleChange}
value={sub_category}
label="select from subcategories"
required
></FormInput>
<FormInput
type="text"
name="product_name"
handleChange={handleChange}
value={product_name}
label="product name"
required
></FormInput>
{createUI()}
<div>
<CustomButton
onClick={addClick}
type="button"
style={{ margin: "14px" }}
>
Add More Fields
</CustomButton>
<CustomButton type="submit" style={{ margin: "12px" }}>
Upload Product
</CustomButton>
</div>
</form>
</div>
);
};
export default ProductUpload;

FormInput组件的代码

import "./forminput.scss";
const FormInput = ({
handleChange,
label,
customwidth,
// register, //useForm hook property to handel change automatically
...otherProps
}) => (
<div className="group" style={{ width: customwidth }}>
<input
className="form-input"
onChange={handleChange}
// ref={register}
{...otherProps}
/>
{label ? (
<label
className={`${
otherProps.value.length ? "shrink" : ""
} form-input-label`}
>
{label}
</label>
) : null}
</div>
);
export default FormInput;

我看到您在handleChange函数中使用i来了解product_specs的索引。但对于product_name或product_category等其他状态,i的值是未定义的。所以我认为您可以检查i是否未定义。

const handleChange = (e, i) => {
console.log(e.target.value, i);
const { name, value } = e.target;
setSub_category({ ...sub_category, [name]: value });
setProduct_name({ ...product_name, [name]: value });
const p_specs = [...product_specs];
if(i) {
product_specs[i][name] = value;
setProduct_specs(p_specs); //This is 100% right.
}
};

我认为它不会影响其他组件,因为i只对product_specs有价值。

嘿,伙计们,这很容易,我不需要使用任何Object.key。可能有很多选项,但在我的情况下,我认为这是最简单的方法。在此处共享我的最终代码。

import FormInput from "../Forminput/forminput";
import CustomButton from "../Custombutton/custombutton";
import axios from "axios";
const ProductUpload = () => {
const [sub_category, setSub_category] = useState({ sub_category: "" });
const [product_name, setProduct_name] = useState({ product_name: "" });
const [product_image, setProduct_image] = useState("");
const [product_specs, setProduct_specs] = useState([
{
specification: "",
specvalue: "",
},
]);
//note VIMP to add square bracket for array
const imageSelectedHandler = (event) => {
setProduct_image({ product_image: event.target.files[0] });
};
// const imageUploadHandler = () => {
//   const fd = new FormData();
//   fd.append("product_image", product_image, product_image.name); //.name is Imp as name is property of file
// };
const handleChange1 = (e) => {
const { name, value } = e.target;
setSub_category({ ...sub_category, [name]: value });
setProduct_name({ ...product_name, [name]: value });
};
const handleChange2 = (e, i) => {
const { name, value } = e.target;
const p_specs = [...product_specs];
p_specs[i][name] = value;
setProduct_specs(p_specs); //This is 100% right.
};
//to add extra input field
const addClick = () => {
// setProduct_specs([...product_specs, { specification: "", specvalue: "" }]); //this is 100% right
//also 100% correct alternative to above line
const p_specs = [...product_specs];
p_specs.push({ specification: "", specvalue: "" });
setProduct_specs(p_specs);
};
//to remove extra input field
const removeClick = (i) => {
const p_specs = [...product_specs];
p_specs.splice(i, 1);
setProduct_specs(p_specs);
};
const handleSubmit = async (event) => {
event.preventDefault();
const newProduct = {
sub_category,
product_name,
product_image,
product_specs,
};
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(newProduct);
const res = await axios.post("/api/product", body, config);
console.log(res.data);
} catch (error) {
console.error(error.response.data);
}
};
const createUI = () => {
return product_specs.map((item, i) => {
return (
<div key={i} className="inputgroup">
<FormInput
type="text"
name="specification"
handleChange={(e) => handleChange2(e, i)}
value={item.specification}
label="specification"
required
customwidth="300px"
></FormInput>
<FormInput
type="text"
name="specvalue"
handleChange={(e) => handleChange2(e, i)}
value={item.specvalue}
label="specification values seperated by quomas"
required
></FormInput>
<CustomButton
onClick={() => removeClick(i)}
type="button"
value="remove"
style={{ margin: "12px" }}
>
Remove
</CustomButton>
</div>
);
});
};
return (
<div className="container">
<form
action="/upload"
method="post"
className="form"
onSubmit={handleSubmit}
encType="multipart/form-data"
>
<h3 style={{ color: "roboto, sans-serif" }}>
Add new product to the database
</h3>
<div
style={{
display: "flex",
height: "200px",
width: "200px",
border: "2px solid #DADCE0",
borderRadius: "6px",
position: "relative",
}}
>
<input
// style={{ display: "none" }}
type="file"
accept="image/*"
onChange={imageSelectedHandler}
multiple={false}
name="product_image"
/>
{/* <CustomButton >
Select Image
</CustomButton>
<CustomButton
//  onClick={imageUploadHandler}
>
Upload
</CustomButton> */}
{/*as per brad- type = "submit" value="submit"  this should not be used, file should upload with the form submit */}
<div>
<img
style={{
width: "100%",
height: "100%",
}}
alt="#"
/>
</div>
</div>
<FormInput
type="text"
name="sub_category"
handleChange={handleChange1}
value={sub_category.sub_category}
label="select from subcategories"
required
></FormInput>
<FormInput
type="text"
name="product_name"
handleChange={handleChange1}
value={product_name.product_name}
label="product name"
required
></FormInput>
{console.log(product_name)}
{console.log(product_specs)}
{createUI()}
<div>
<CustomButton
onClick={addClick}
type="button"
style={{ margin: "14px" }}
>
Add More Fields
</CustomButton>
<CustomButton type="submit" style={{ margin: "12px" }}>
Upload Product
</CustomButton>
</div>
</form>
</div>
);
};
export default ProductUpload;

相关内容

  • 没有找到相关文章

最新更新