我想使用 Axios 从我的列表中删除一本书。我使用我的数据库的 URL + id,但我找不到在 URL 中指定 id 的方法,它保持未定义状态。
看起来像这样:
export default class ListBooks extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, data: [] }
}
componentDidMount() {
Axios.get(process.env.REACT_APP_API_PATH_BOOKS)
.then(res => {
this.setState({ data: res.data });
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
handleChange = event => {
this.setState({ number: event.target.value });
}
/**
* Use to delete a book by the id.
*/
handleDelete = () => {
const id = this.data.number
console.log(id);
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);
cible.remove();
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
render() {
const { data } = this.state;
return (
<div>
<Container>
{data.map(books =>
<div key={books.number}>
<ListGroup>
<ListGroup.Item disabled id={"book-admin" + data.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>
)
}
}
每次我按下“删除”按钮时都会出现此错误:类型错误:无法读取未定义的属性“编号”。
有人可以告诉我我做错了什么吗? 或者我需要什么才能获得所需的所有信息? 谢谢
最佳答案
应该是:
const id = this.state.data.number
不是
const id = this.data.number
将来找到它的一个好技巧是始终从未定义的内容回溯以找到最后定义的内容并从那里开始工作
关于javascript - 类型错误:无法读取未定义的属性 'number',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62511326/