我正在进行用户地址管理,并将其保存到mongodb中,就像在地址数组中一样,但是现在存储为对象。下面是要存储在数据库中的数据示例。
{
"personname": "Customer_1",
"mobile": "00000000000"
},
{
"personname": "Customer_2",
"mobile": "00000000001"
}
const [prifletab, setPrifletab] = useState(true);
const [addressestab, setAddressestab] = useState(false);
const [values, setValues] = useState({
name: "",
email: "",
addresses: [],
loading: false,
error: false,
redirectToProfile: false,
formData: ""
});
return (
<form className="mb-3" onSubmit={clickSubmit}>
<h3>Profile Update </h3>
<div
className="prifletab"
style={{ display: prifletab ? "block" : "none" }}
>
<div className="form-group">
<label className="text-muted">Name</label>
<input
onChange={handleChange("name")}
type="text"
className="form-control"
value={name}
/>{" "}
</div>
<div className="form-group">
<label className="text-muted">Email</label>
<input
onChange={handleChange("email")}
className="form-control"
value={email}
/>
</div>
</div>
<div
className="addressestab"
style={{ display: addressestab ? "block" : "none" }}
>
<div className="form-group">
<label className="text-muted">Contact Person Name</label>
<input
onChange={handleChange("contactperson")}
type="text"
className="form-control"
/>
</div>
<div className="form-group">
<label className="text-muted">Mobile</label>
<input
onChange={handleChange("contact")}
type="text"
className="form-control"
/>
</div>
</div>
<button className="btn btn-outline-primary">Submit</button>
</form>
);
我想问一下,如果需要帮助的话,如何在地址数组中存储数组值。预先感谢您的宝贵时间。
答案 0 :(得分:1)
您试图将值分配给adrss
,就好像它是一个对象一样,但是它是一个数组。如果只需要将一个对象保存到数组,则可以这样做:
address = {[name]: event.target.value};
formData.set(addresses, [address]);
setValues({ ...values, addresses: [address] });
或者如果您需要添加地址而不是覆盖它:
setValues({ ...values, addresses: [...values.addresses, address] });