从ReactJ中的阵列中删除项目

发布于 2025-01-21 22:26:02 字数 3914 浏览 2 评论 0原文

我正在学习反应,我似乎无法弄清楚如何从数组中删除项目。我已经尝试了几种方法,但是它要么删除了整个数组,要么在数组中的一个多个项目,因此我找不到任何工作解决方案。这是我的代码:

app.js:

import React, { useState } from 'react';
import Education from './Education';

export default function App() {
  const [educationArray, setEducationArray] = useState([]);
  const handleDeleteEduItem =(id)=>{
  
    const eduArrayToSplice = [...educationArray]
    const newEduArray = eduArrayToSplice.splice(id, 1)
    
    setEducationArray(newEduArray)
    console.log(id)
  }
  return (
    <div className="App">
    <div className="edit-mode">
    <h4>Education</h4>
    <button onClick={()=>{setEducationArray([...educationArray, <Education id={educationArray.length} handleDeleteButton={handleDeleteEduItem}/>])}}>add new</button>
    {educationArray.map((eduItem, i)=><div className="eduItem" key={i}>{eduItem}</div>)}
       
     
    </div>
    </div>
      
  );
}

以及功能组件:

import React, { useState} from 'react';

function Education(props)

 {
       const [schoolName, setSchoolName] = useState('');
       const [major, setMajor] = useState('');
       const [studyFrom, setStudyFrom] = useState('')
       const [studyTo, setStudyTo] = useState('');
       const [degree, setDegree] = useState('');
       const [displayEducationSection, setEducationSection] = useState(false)
      
    

       const changeSchoolName = (e) => {
              setSchoolName(e.target.value);
            };
          
       const changeMajor = (e) => {
              setMajor(e.target.value);
            };
       const changeStudyFrom =(e)=> {
              setStudyFrom(e.target.value);
            };
       const changeStudyTo =(e)=> {
              setStudyTo(e.target.value)
            };
       const changeDegree =(e) => {
              setDegree(e.target.value);
            };
       const flipEducationSection =()=> {
              setEducationSection(!displayEducationSection)
            };
   

          
          
    return(
        <div className="education-section">
            {displayEducationSection ? 
            <div>
              <p>School Name: {schoolName}</p>
              <p>Major: {major}</p>
              <p>from: {studyFrom}</p>
              <p>to: {studyTo}</p> 
              <p>Degree: {degree}</p> 

            </div>
            :
            <form onSubmit={(e)=>e.preventDefault()} className="education-form">
            <label>
                   School Name:<input value={schoolName} onChange={changeSchoolName} />
            </label>
            <label>
                   Major:<input value={major} onChange={changeMajor} />
            </label>
            <label>
                   From:<input value={studyFrom} onChange={changeStudyFrom} />
            </label>
            <label>
                   To:<input value={studyTo} onChange={changeStudyTo} />
            </label>
            <label>
                   Degree:<input value={degree} onChange={changeDegree} />
            </label>

                
            </form>}
            <button onClick={flipEducationSection}>{displayEducationSection ? 'edit' : 'save'}</button>
            <button onClick={()=>props.handleDeleteButton(props.id)}>delete</button>
        </div>
    )

}



export default Education;

我还使用以下功能尝试从数组中删除项目,但是它不会删除单击项目,而是删除了其后的所有项目:

const handleDeleteEduItem =(id)=>{
  const newEduArray = educationArray.filter((item)=>educationArray[item] !== id)
  
  setEducationArray(newEduArray)
  console.log(educationArray)
}

I am learning React and I can't seem to figure out how to remove an item from an array. I have tried couple of ways but it either removes the entire array or more than one item in the array so I can't find any working solution. Here is my code:

App.js:

import React, { useState } from 'react';
import Education from './Education';

export default function App() {
  const [educationArray, setEducationArray] = useState([]);
  const handleDeleteEduItem =(id)=>{
  
    const eduArrayToSplice = [...educationArray]
    const newEduArray = eduArrayToSplice.splice(id, 1)
    
    setEducationArray(newEduArray)
    console.log(id)
  }
  return (
    <div className="App">
    <div className="edit-mode">
    <h4>Education</h4>
    <button onClick={()=>{setEducationArray([...educationArray, <Education id={educationArray.length} handleDeleteButton={handleDeleteEduItem}/>])}}>add new</button>
    {educationArray.map((eduItem, i)=><div className="eduItem" key={i}>{eduItem}</div>)}
       
     
    </div>
    </div>
      
  );
}

And the functional component:

import React, { useState} from 'react';

function Education(props)

 {
       const [schoolName, setSchoolName] = useState('');
       const [major, setMajor] = useState('');
       const [studyFrom, setStudyFrom] = useState('')
       const [studyTo, setStudyTo] = useState('');
       const [degree, setDegree] = useState('');
       const [displayEducationSection, setEducationSection] = useState(false)
      
    

       const changeSchoolName = (e) => {
              setSchoolName(e.target.value);
            };
          
       const changeMajor = (e) => {
              setMajor(e.target.value);
            };
       const changeStudyFrom =(e)=> {
              setStudyFrom(e.target.value);
            };
       const changeStudyTo =(e)=> {
              setStudyTo(e.target.value)
            };
       const changeDegree =(e) => {
              setDegree(e.target.value);
            };
       const flipEducationSection =()=> {
              setEducationSection(!displayEducationSection)
            };
   

          
          
    return(
        <div className="education-section">
            {displayEducationSection ? 
            <div>
              <p>School Name: {schoolName}</p>
              <p>Major: {major}</p>
              <p>from: {studyFrom}</p>
              <p>to: {studyTo}</p> 
              <p>Degree: {degree}</p> 

            </div>
            :
            <form onSubmit={(e)=>e.preventDefault()} className="education-form">
            <label>
                   School Name:<input value={schoolName} onChange={changeSchoolName} />
            </label>
            <label>
                   Major:<input value={major} onChange={changeMajor} />
            </label>
            <label>
                   From:<input value={studyFrom} onChange={changeStudyFrom} />
            </label>
            <label>
                   To:<input value={studyTo} onChange={changeStudyTo} />
            </label>
            <label>
                   Degree:<input value={degree} onChange={changeDegree} />
            </label>

                
            </form>}
            <button onClick={flipEducationSection}>{displayEducationSection ? 'edit' : 'save'}</button>
            <button onClick={()=>props.handleDeleteButton(props.id)}>delete</button>
        </div>
    )

}



export default Education;

I've also used the following function to try to remove an item from the array, but it doesn't remove the clicked item but removes all items that come after it:

const handleDeleteEduItem =(id)=>{
  const newEduArray = educationArray.filter((item)=>educationArray[item] !== id)
  
  setEducationArray(newEduArray)
  console.log(educationArray)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落花浅忆 2025-01-28 22:26:02

我认为您不想直接过滤状态。相反,您可以做的是:

setEducationArray((cv) => cv.filter((e) => e.id !== id ))

这样,您就可以访问您的教育节目(CV)中的当前值,并过滤以获取所有元素,而E.ID不等于您给出的ID的所有元素。

编辑:

公平地说,我不确定您的数组最终如何。但是,如果它是一系列对象,则每个对象都有自己的ID。然后,我建议我上面写的东西。

I think you don't want to filter directly the state. What you could do instead is:

setEducationArray((cv) => cv.filter((e) => e.id !== id ))

This way you get to access the current value in your educationArray state (cv), and filter that to get all elements where the e.id is not equal to the id you have given to your id.

Edit:

To be fair, I'm not sure how your array eventually looks like. But if it was an array of objects, with each object having its own id. Then I would suggest the thing I wrote above.

吃兔兔 2025-01-28 22:26:02

您无法使用相同的内存位置直接更新状态。
您必须创建新的内存才能更新数组,然后更新组件状态。您将很快看到UI上的更改。

否则,此功能将帮助您从数组中删除单个项目。
你必须

确保您的ID对于每个项目都唯一。

const andleteleteleteDuitem =(id)=&gt; {

const eduArrayToSplice = [...educationArray.filter(item)=>item.id!==id)]   
setEducationArray(newEduArray)
console.log(id)

}

you can not directly update the state with using same memory location.
you have to create new memory to updated array and then update the component state. you will see quickly changes on UI.

else this function will help you to remove single item from array.
you have to

ensure that your id should be unique for each item.

const handleDeleteEduItem =(id)=>{

const eduArrayToSplice = [...educationArray.filter(item)=>item.id!==id)]   
setEducationArray(newEduArray)
console.log(id)

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文