首页 > 解决方案 > 收到 `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

标签: reactjs

解决方案


问题出在储备功能上。

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。

我将如何单独更新按钮上的值?

你可以试试:

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>

推荐阅读