【发布时间】:2021-06-17 20:55:50
【问题描述】:
在这里反应新手。 我试图在单击按钮时减少数量值。当我单击按钮时,我看到所有按钮旁边显示一个 NaN 值。我怎样才能避免 NaN 错误?我在这里犯了什么错误,我将如何单独更新按钮上的值?谢谢你。数据和代码如下。
{
"id": 1,
"title": "Python Crash Course",
"author": "Eric Matthes",
"quantity": 5
},
{
"id": 2,
"title": "Head-First Python",
"author": "Paul Barry",
"quantity": 2
},
{
"id": 3,
"title": "Invent Your Own Computer Games with Python",
"author": "Al Sweigart",
"quantity": 1
}
下面是我的 React 代码。
class BooksComponent extends Component{
constructor(){
super()
this.state ={
booksData: []
}
this.reserve = this.reserve.bind(this)
}
componentDidMount() {
axios.get('/library')
.then(res => {
const booksData = res.data
this.setState({ booksData })
})
}
render() {
return (
<div className="App">
{this.state.booksData.map(book => {
const {id, title, author, quantity} = book
return (
<div>
<p>{id} - {title} - {author}</p>
<button onClick={this.reserve}>Reserve {quantity}</button>
<span>{this.state.quantity}</span>
</div>
);
})
}
</div>
)
}
reserve(){
console.log('Reserved')
this.setState({
quantity: this.state.booksData.quantity-1
}
)
console.log(this.state)
}
}
export default BooksComponent
【问题讨论】:
标签: reactjs