这一个的行为让我感到困惑。通过点击“添加按钮”几次创建了一个列表。从列表中删除一个项目(通过点击项目旁边的“删除”)正确地从列表中删除项目(并更新状态),但显示显示最后一个项目被删除,而您选择删除的项目仍然存在。我没有正确更新状态吗:
import { useState } from "react"
export const App = () => {
const [records, setRecords] = useState({ data: [], errState: false })
const addRecord = () => {
let newList = [...records.data]
newList.push(`This Will Be Record ${newList.length}`)
console.log(newList)
setRecords(ps => ({ ...ps, data: newList }))
}
const delRecord = ({ target }) => {
const id = parseInt(target.getAttribute("data-row"))
let newList = [...records.data]
newList.splice(id, 1)
setRecords(ps => ({ ...ps, data: newList }))
}
const buildRows = () => {
return records.data.map((r, rndx) => {
return (
<div style={{ display: "flex",marginBottom:"10px" }}>
<div style={{ flex: 1, paddingRight: "20px" }}><input id={`test-${rndx}`}/></div>
<div style={{ width: "50px" }}><button onClick={delRecord} data-row={rndx}>Delete</button></div>
</div>
)
})
}
return (
<div style={{ width: "800px", margin: "0 auto", textAlign: "center" }}>
{buildRows()}
<button onClick={addRecord}>Add Record</button>
</div>
)
}
字符串
CodeSandbox
1条答案
按热度按时间egmofgnx1#
考虑为每个不是从其数组索引派生的项目设置唯一的id。在渲染项目时使用此id值作为
key
prop,以确保React从DOM中删除适当的元素:个字符