简体   繁体   中英

Antd item.list removes always removes first last element

Hi there I made simple antd list where user can add, remove edit list. But the problem is that when i add, edit list verything works as it should. But when i remove item from a list, antd always remove last item from a list. Although i can remove any item.

  const [employeeList, setEmployeeList] = useState([])
    <List
      dataSource={employeeList}
      renderItem={(item, index) => (
       <List.Item id='listItem' >
         <Input 
          id='listItem-input'
          defaultValue={item.name} 
          onChange={(i) => {
            employeeList[index].name = i.target.value
            setEmployeeList(answerList)   
          }}
        />
        <span className='removeItem' 
          onClick={() => {
            let newList = setEmployeeList
            newList[index] = undefined
            setEmployeeList(newList.filter(e => e))
           }}
         >
           <CloseOutlined/>
         </span>
       </List.Item>
     )}
  />

I checked in console items in state gets removed, although it still stays in item.list

First of all I would recomend deleting items with splice()

so rather then this 3 lines in onClick (in remove) just

employeeList.splice(index,1)

Edit:

With your approach you probably want:
 let newList = employeeList newList[index] = undefined

Turns out i had to use a keys. List.Item wasn't registering changes without keys and was just deleting last item, on any change.

<List.Item id='listItem' key={item.answer} >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM