【问题标题】:React: deletion of component from an array of componentsReact:从组件数组中删除组件
【发布时间】:2021-02-04 16:05:57
【问题描述】:

我正在使用 useState 钩子初始化 myComponents 数组

const [myComponents, setMyComponents] = useState([])

然后我在单击按钮时将组件添加到数组中

setMyComponents([...myComponents, <MyComponent />])

我的组件:

function MyComponent(props) {
  return (
    <div class="flex">
      <button>DELETE</button>
      <p>Some text...</p>
    </div>
  )
}

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

请告诉我如何从数组中删除特定的 MyComponent,以免影响后续删除。

【问题讨论】:

  • stackoverflow.com/questions/53976609/…状态下存储组件或任何复杂对象不是一个好主意
  • @diedu 谢谢,我认为这个问题将引导我得到我想要的......再次感谢
  • 为什么不用 Map 而不是数组呢?
  • @PiyushN 是的,我必须将组件所需的数据保存在一个数组中,并将使用 .map 来创建组件数组。

标签: reactjs react-hooks


【解决方案1】:

这不是你在 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} />
     }
  )
}

【讨论】:

  • 我是 React 新手,除了回答我的问题外,我从您的回答中学到了很多东西。再次感谢(Y)
猜你喜欢
  • 2018-01-24
  • 2022-12-03
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2019-10-14
  • 2020-11-28
  • 2018-09-15
  • 1970-01-01
相关资源
最近更新 更多