微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反应中 onChange 事件的问题

如何解决反应中 onChange 事件的问题

我厌倦了在输入复选框上选中和取消选中。 事实上,我有一个复选框项目列表,我从 API 中获取它们,然后我想将它们划掉或不选中它们并发送到数据库。我越过了其中一些,我可以成功地从数据库获取交叉的复选框。现在我尝试取消选中它们,然后再次发布它们。下一次,当我重新加载页面时,我看到仍然有交叉的复选框。

在这里你可以看到代码。 任何人都可以解决我的难题吗?

她你可以看到我的代码部分。 谢谢。

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,...]
              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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。