javascript - 错误:this.state.data[index].number 打印索引未定义
问题描述
我需要使用带有 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>
)
}
}
解决方案
你没有通过索引。
试试这个:
onClick={() => this.handleDelete(index)}
和
handleDelete = (index) => {
发送删除请求后,如果您想从状态数组中删除该项目,您可以使用以下命令:
handleDelete = (index) => {
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();
this.setState(prevState => ({ ...prevState, data: prevState.data.filter((book) => book.number !== id) }))
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
推荐阅读
- flutter - Flutter 中从屏幕外滑动的小部件?类似于 Android 8 应用程序抽屉
- java - twitter4j 搜索完整的 7 天范围
- loopbackjs - Loopback - 如何将访问令牌分配给角色?
- javascript - 从反应组件传递数据
- ssl - Neo4j 和 LetsEncrypt
- android - 如何修复“错误:Flutter 目录不是 GitHub 项目的克隆”。尝试安装颤振时出错?
- javascript - ExtendScript 中正则表达式的语法错误(Javascript ECMA-262 — 版本 3)
- python - 我的 cookie 阅读器不工作
- sql-server - 如何在 SQL Server 中检索长查询
- css - 如何使用关键帧中途停止进度条动画