Reactjs 反应:从组件数组中删除组件

Reactjs 反应:从组件数组中删除组件,reactjs,react-hooks,Reactjs,React Hooks,我正在用useStatehook初始化myComponentsarray const[myComponents,setMyComponents]=useState([] 然后单击一个按钮,将组件添加到数组中 setMyComponents([…myComponents,]) MyComponent: 功能MyComponent(道具){ 返回( 删除 一些文字 ) } 当按下任何删除按钮时,应从myComponents数组中删除相关的MyComponent。我不知道如何获取对我必须删除的组

我正在用
useState
hook初始化
myComponents
array

const[myComponents,setMyComponents]=useState([]
然后单击一个按钮,将组件添加到数组中

setMyComponents([…myComponents,])
MyComponent:

功能MyComponent(道具){
返回(
删除
一些文字

) }
当按下任何删除按钮时,应从
myComponents
数组中删除相关的MyComponent。我不知道如何获取对我必须删除的组件的引用。我无法使用数组索引,因为当从数组中删除第一个组件时,以前的索引不再有效


请让我知道如何从数组中删除特定MyComponent,以便它不会影响后续的删除。

这不是您在react中呈现数据的方式,通常您会映射一个数据列表并呈现如下所示的组件,因此,当您需要删除某个项目时,只需从数据列表中删除该项目,Listcomponent将使用新数据重新呈现:

function MyComponent(props) {
const {index,text,deleteItem} = props
  return (
    <div class="flex">
      <button onClick={e=>deleteItem(index)}>DELETE</button>
      <p>{text}</p>
    </div>
  )
}

function MyComponentList(props) {
  const [mydata, setmydata] = useState(["text1","text2","text3"])

 const deleteItem=(index)=>{
      const filterdData= [...mydata].filter((data,i)=> i != index)
      setmydata(filterdData)
 }
  return (
     {
        mydata.map((text,index)=><MyComponent key={index} text={text} index={index} deleteItem= {deleteItem} />
     }
  )
}

功能MyComponent(道具){
常量{index,text,deleteItem}=props
返回(
deleteItem(索引)}>DELETE
{text}

) } 功能MyComponentList(道具){ const[mydata,setmydata]=useState([“text1”、“text2”、“text3”]) 常量deleteItem=(索引)=>{ 常量filterdData=[…mydata].filter((数据,i)=>i!=索引) setmydata(FilterData) } 返回( { mydata.map((文本,索引)=> } ) }
在@diedu状态下存储组件或任何复杂对象不是一个好主意,谢谢,我想这个问题会引导我得到我想要的…再次感谢为什么不使用Map而不是数组?@PiyushN是的,我必须将组件所需的数据保存在数组中,并使用.Map创建组件数组.我是个新手,除了回答我的问题之外,我还从你的回答中学到了很多。再次感谢(Y)