【发布时间】:2020-10-19 19:37:57
【问题描述】:
我需要使用 axios 的 DELETE 请求从列表中删除一本书。我使用 this.state.data[index].number 获取书的编号并将其传递给 URL,但控制台打印错误“未定义索引”。我该如何解决这个错误?
否则,当我用特定索引(如 1)替换索引时,我会得到添加到 URL 的书的编号,但我的变量 cible(也需要该编号来删除书)打印 null...
这是我的代码:
export default class ListBooks extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, data: [], number: "" }
}
componentDidMount() {
Axios.get(process.env.REACT_APP_API_PATH_BOOKS)
.then(res => {
this.setState({ data: res.data });
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
/**
* Use to delete a book by the id.
*/
handleDelete = () => {
const id = this.state.data[index].number
Axios.delete(process.env.REACT_APP_API_PATH_BOOKS + id)
.then(res => {
console.log(res);
console.log(res.data);
let cible = document.getElementById("book-admin" + id);
console.log(cible);
cible.remove();
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
render() {
const { data } = this.state;
return (
<div>
<Container>
{data.map((books, index) =>
<div key={books.number}>
<ListGroup>
<ListGroup.Item disabled id={"book-admin" + data.number}>{books.number}. {books.name} {books.author}
</ListGroup.Item>
</ListGroup>
<Button variant="outline-warning" size="sm" className="btn-admin-change" id={data.number} onClick={this.props.handleUpdate}>Modifier</Button>
<Button variant="outline-danger" size="sm" className="btn-admin-change" onClick={this.handleDelete}>Supprimer</Button>
</div>
)}
</Container>
</div>
)
}
}
【问题讨论】:
-
handleDelete没有传递给它的变量或参数称为index,它也没有在类中全局定义,这就是原因。
标签: javascript reactjs axios state http-delete