gpt4 book ai didi

reactjs - 收到 `children` 属性的 NaN。如果这是预期的,则将该值转换为字符串

转载 作者:行者123 更新时间:2023-12-04 09:30:37 24 4
gpt4 key购买 nike

在这里 react 新手。
我试图在单击按钮时减少数量值。当我单击按钮时,我看到所有按钮旁边都显示一个 NaN 值。我怎样才能避免 NaN 错误?我在这里犯了什么错误,我将如何单独更新按钮上的值?谢谢你。数据和代码如下。 enter image description here

{
"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

最佳答案

问题出在储备功能上。

this.state.booksData.quantity - 1 
this.state.booksData是一个数组,无法正确访问数量。 this.state.booksData.quantityundefined
undefined - number = NaN
您需要通过 bookData 项的 id 过滤数组,如下所示:
reserve(id) {
this.setState({
quantity: this.state.booksData.find(item => item.id === id).quantity - 1
})
}
并在 onClick 中传递 bookData 项目的 id。

how would I individually update the values on the buttons?


你可以试试:
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>

关于reactjs - 收到 `children` 属性的 NaN。如果这是预期的,则将该值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com