如何在 axios 和 react 中实现 DELETE 方法?



我无法实现删除按钮。 我有 api 端点 'DELETE/.../{id}'。 有蜂服务.js:

deleteById(id) {
return axios.delete(`${ACCOUNT_API_BASE_URL}/${id}`)
}

这是我的班级:

class Account extends Component {
constructor(props) {
super(props);
this.state = {
item: {
id: props.match.params.id,
name: '',
email: '',
password: '',
link: ''
}
};
this.deleteById = this.deleteById.bind(this);
}
componentDidMount() {
// eslint-disable-next-line
if (this.state.item.id === -1) {
return -1
}
ApiService.fetchAccountById(this.state.item.id)
.then(response => this.setState({
item: {
name: response.data.name,
email: response.data.email,
password: response.data.password,
link: response.data.link
}
}))
}

deleteById(id) {
ApiService.deleteById(id)
.then(res => console.log(res.data))
}
render() {
return (
<div>
<h3>{this.state.item.name}</h3>
<ul>
{this.state.item.id}
<li className={c.itemEmail}>Email: {this.state.item.email}</li>
<li>Password: {this.state.item.password}</li>
<li>Link: {this.state.item.link}</li>
</ul>
<button onClick={this.deleteById(this.state.item.id)}>Delete</button>
</div>
)
}
}

它在请求页面(获取方法(后删除数据,但不是通过单击删除按钮。

如果我将this.deleteById设置为<button onClick=到 ,我会收到: "删除 http://localhost:8080/api/.../undefined 400">

首先,从 componentDidMount 中的项中删除id属性:

ApiService.fetchAccountById(this.state.item.id)
.then(response => this.setState({
item: { // now item doesn't have id anymore
name: response.data.name,
email: response.data.email,
password: response.data.password,
link: response.data.link
}
}))

所以保持你的id像这样:

ApiService.fetchAccountById(this.state.item.id)
.then(response => this.setState({
item: {
id: this.state.item.id,
name: response.data.name,
email: response.data.email,
password: response.data.password,
link: response.data.link
}
}))

其次,您正在执行函数而不是将函数传递给 onClick,请将您的 onClick 值更改为:

onClick={() => {this.deleteById(this.state.item.id)}}
<button onClick={() => this.deleteById(this.state.item.id)}>Delete</button>

最新更新