我正在显示一个简单的表格,其中填充了来自 API 的数据。该表具有 post/put/delete/edit 请求功能。 DELETE 请求有时成功,有时不成功。从控制台输出中,我多次按下删除按钮,然后它就起作用了。我相信该组件尚未完全呈现,并且在进行 axios 调用时,“event.target.id”值对 DOM 不可用。
-如何告诉组件和/或删除函数等待 id 值?
-我应该使用 state 来存储 id 属性还是 data-contactid 属性而不是 event.target.id?
谢谢。
class AllContacts extends Component {
state = {
contactData: [],
id: '',
}
componentDidMount() {
apiClient.get('contacts', {
onSuccess: ({ data }) => {
this.setState({contactData: data})
},
onError: () => { /* would be cool to do something here */ }
})
.catch(err => console.log('error: ', err))
}
handleSubmit = (event) => {
event.preventDefault();
console.log(event)
apiClient.delete(`contacts/${event.target.id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
renderTable = () => {
return (
<div>
<Table>
<TableHead>
<TableRow>
<TableCell>
<SimpleModal />
</TableCell>
</TableRow>
<TableRow>
<TableCell>AVATAR</TableCell>
<TableCell>FIRST NAME</TableCell>
<TableCell>LAST NAME</TableCell>
<TableCell>EDIT</TableCell>
<TableCell>DELETE</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.contactData ? this.state.contactData.map((contact, i) => (
<TableRow key={i}>
<TableCell>
Avatar{/* <img src={this.state.contactData.avatarUrl} width="100" height="100" alt="Avatar"/> */}
</TableCell>
<TableCell>
{contact.firstName}
</TableCell>
<TableCell>
{contact.lastName}
</TableCell>
<TableCell>
<Button variant="raised" color="primary">
EDIT
</Button>
</TableCell>
<TableCell>
<Button data-contactid={contact.id} id={contact.id} onClick={this.handleSubmit} variant="raised" color="secondary">
DELETE
</Button>
</TableCell>
</TableRow>
))
:null}
</TableBody>
</Table>
</div>
)
}
render() {
console.log(this.state)
return (
<div>
{this.renderTable()}
</div>
)
}
}
export default AllContacts
最佳答案
不用参加事件也可以试试,
<Button data-contactid={contact.id} id={contact.id} onClick={()=>this.handleSubmit(contact.id)} variant="raised" color="secondary">
并将 handleSubmit 函数更改为,
handleSubmit = (id) => {
console.log(id)
apiClient.delete(`contacts/${id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
关于javascript - 如何从按钮中正确检索事件 ID 并用于删除 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50244290/