reactjs - 收到 `children` 属性的 NaN。如果这是预期的,请将值转换为字符串
问题描述
在这里反应新手。我试图在单击按钮时减少数量值。当我单击按钮时,我看到所有按钮旁边显示一个 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
}
下面是我的反应代码。
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
解决方案
问题出在储备功能上。
this.state.booksData.quantity - 1
this.state.booksData
是一个数组,无法正确访问数量。
this.state.booksData.quantity
是undefined
undefined - number = NaN
您需要通过 bookData 项的 id 过滤数组,如下所示:
reserve(id) {
this.setState({
quantity: this.state.booksData.find(item => item.id === id).quantity - 1
})
}
并在 onClick 中传递 bookData 项的 id。
我将如何单独更新按钮上的值?
你可以试试:
reserve(id) {
this.setState({
booksData: this.state.booksData.map(item => {
if (item.id === id) {
return { ...item, quantity: item.quantity - 1};
} else {
return item;
}
})
})
}
在渲染中:
<span>{quantity}</span>
推荐阅读
- sqlite - 按时间戳从数据库中选择事件
- python - python seaborn为jointplot设置xlim和ylim,去掉上面和右边的分布信息
- java - 对 TreeSet 的并发访问似乎不起作用
- mongodb - 如何在 mongodb 中获取特定的匹配字段值?
- vb.net - 验证从 VB.net 发送的 Outlook 电子邮件是否实际发送
- python - PyAutoGui - 单击特定位置后,它会单击未定义的位置
- android - 如何在 Kotlin 中创建一个简单的倒数计时器?
- c# - C# 如何向连接到我的服务器的所有客户端发送数据?
- reactjs - 如何通过属性删除reactjs中的元素?
- c++ - 不能在函数 C++ 中使用覆盖