反应中onChange事件的麻烦问题
Trouble problem with onChange event in react
我厌倦了在输入复选框上选中和取消选中。
事实上,我有一个复选框项目列表,我从 API 中获取它们,然后我想越过或不选中它们并发送到数据库。我划掉了其中的一些,我可以成功地从数据库中获取划线的复选框。现在我尝试取消选中它们,然后我再次 post 它们。下次,当我重新加载页面时,我看到仍然有交叉的复选框。
在这里你可以看到代码。
谁能解开我的谜题?
她你可以看到我的部分代码。
谢谢。
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState("");
const [selectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
let intIds = response?.data?.interests; // intIds it is Array like intIds =[{"id": 1, "name": "drink"}, ...] or empty
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = [];
for (let inter of response.data) { //here: response.data=[{"id": 1, "name": "drink"}, ...]
interestItems.push(
<div className="col-6" key={inter.id}>
<div className="row">
<div className="col-2">
<input
key={inter.id}
id={inter.id}
name="newsletter"
type="checkbox"
onChange={(e) =>{ console.log(e, e.target)
return interestChange(e.target)}}
/>
</div>
<div className="col-10">
<p className="p-14">{inter.name}</p>
</div>
</div>
</div>
);
}
setInterests(interestItems);
for (let elem of intIds) {
document.getElementById(elem.id).setAttribute("checked", "checked");
selectedInterests.push(elem.id);
}
})
.catch((err) => {
console.log(err);
});
});
}, []);
const interestChange = (elem) => {
console.log(elem, elem.checked, elem.id);
console.log(selectedInterests);
if (elem.checked) {
selectedInterests.push(parseInt(elem.id));
console.log(selectedInterests);
}
else {
let newInterests = selectedInterests;
newInterests.splice(newInterests.indexOf(parseInt(elem.id)), 1);
console.log(newInterests);
}
}
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">
{interests}
</div>
</Form>
</div>
</div>
);
}
export default UserProfile;
在这里我试着找到我的难题的解决方案
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState({});
const [selectedInterests, setSelectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
if(Array.isArray(response?.data?.interests)){
setSelectedInterests(response?.data?.interests.map((interest) => interest.id));
}
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = {};
for (let inter of response.data) {
interestItems[inter.id]= inter;
}
setInterests(interestItems);
})
.catch((err) => {
console.log(err);
});
});
}, []);
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">{Object.keys(interests).map((interstId) => {
interstId = +interstId;
let interest = interests[interstId];
//console.log(selectedInterests, interstId,
selectedInterests.indexOf(interstId));
return <div className="col-6" key={interest.id}>
<div className="row">
<div className="col-2">
<input
key={interest.id}
id={interest.id}
name="newsletter"
type="checkbox"
checked = {selectedInterests.indexOf(interstId) > -1 ? "checked" : ""}
onChange={(e) =>{
let index = selectedInterests.indexOf(interstId);
if(index > -1){
selectedInterests.splice(index, 1);
setSelectedInterests([...selectedInterests])
}else{
setSelectedInterests([...selectedInterests, interstId])
}
}}
/>
</div>
<div className="col-10">
<p className="p-14">{interest.name}</p>
</div>
</div>
</div>
})}</div>
</Form>
</div>
</div>
);
}
export default UserProfile;
我厌倦了在输入复选框上选中和取消选中。 事实上,我有一个复选框项目列表,我从 API 中获取它们,然后我想越过或不选中它们并发送到数据库。我划掉了其中的一些,我可以成功地从数据库中获取划线的复选框。现在我尝试取消选中它们,然后我再次 post 它们。下次,当我重新加载页面时,我看到仍然有交叉的复选框。
在这里你可以看到代码。 谁能解开我的谜题?
她你可以看到我的部分代码。 谢谢。
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState("");
const [selectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
let intIds = response?.data?.interests; // intIds it is Array like intIds =[{"id": 1, "name": "drink"}, ...] or empty
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = [];
for (let inter of response.data) { //here: response.data=[{"id": 1, "name": "drink"}, ...]
interestItems.push(
<div className="col-6" key={inter.id}>
<div className="row">
<div className="col-2">
<input
key={inter.id}
id={inter.id}
name="newsletter"
type="checkbox"
onChange={(e) =>{ console.log(e, e.target)
return interestChange(e.target)}}
/>
</div>
<div className="col-10">
<p className="p-14">{inter.name}</p>
</div>
</div>
</div>
);
}
setInterests(interestItems);
for (let elem of intIds) {
document.getElementById(elem.id).setAttribute("checked", "checked");
selectedInterests.push(elem.id);
}
})
.catch((err) => {
console.log(err);
});
});
}, []);
const interestChange = (elem) => {
console.log(elem, elem.checked, elem.id);
console.log(selectedInterests);
if (elem.checked) {
selectedInterests.push(parseInt(elem.id));
console.log(selectedInterests);
}
else {
let newInterests = selectedInterests;
newInterests.splice(newInterests.indexOf(parseInt(elem.id)), 1);
console.log(newInterests);
}
}
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">
{interests}
</div>
</Form>
</div>
</div>
);
}
export default UserProfile;
在这里我试着找到我的难题的解决方案
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState({});
const [selectedInterests, setSelectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
if(Array.isArray(response?.data?.interests)){
setSelectedInterests(response?.data?.interests.map((interest) => interest.id));
}
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = {};
for (let inter of response.data) {
interestItems[inter.id]= inter;
}
setInterests(interestItems);
})
.catch((err) => {
console.log(err);
});
});
}, []);
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">{Object.keys(interests).map((interstId) => {
interstId = +interstId;
let interest = interests[interstId];
//console.log(selectedInterests, interstId,
selectedInterests.indexOf(interstId));
return <div className="col-6" key={interest.id}>
<div className="row">
<div className="col-2">
<input
key={interest.id}
id={interest.id}
name="newsletter"
type="checkbox"
checked = {selectedInterests.indexOf(interstId) > -1 ? "checked" : ""}
onChange={(e) =>{
let index = selectedInterests.indexOf(interstId);
if(index > -1){
selectedInterests.splice(index, 1);
setSelectedInterests([...selectedInterests])
}else{
setSelectedInterests([...selectedInterests, interstId])
}
}}
/>
</div>
<div className="col-10">
<p className="p-14">{interest.name}</p>
</div>
</div>
</div>
})}</div>
</Form>
</div>
</div>
);
}
export default UserProfile;