【问题标题】:Received NaN for the `children` attribute. If this is expected, cast the value to a string收到 `children` 属性的 NaN。如果这是预期的,请将值转换为字符串
【发布时间】: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


    【解决方案1】:

    问题出在储备功能上。

    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>
    

    【讨论】:

    • 谢谢。我已经尝试使用 parseInt 但我仍然看到同样的错误
    • 更新了!我错了 Javascript 在内部将字符串解析为 int 减法
    • @NachoZullo 您可能需要在运行时更新 setState 方法 b/c 他的状态将如下所示 state ={booksData = [], quantity = 1}
    • @NachoZullo 谢谢!在我使用 {item.quantity} 的渲染中,错误显示“item”未定义。我将如何在渲染中定义或传递项目?还有如何将 id 传递给 onClick?
    • @blackPanther 我又错了:(它的 {quantity}。在 onClick 你可以做 onClick={() => reserve(id)}
    【解决方案2】:

    你可以内联更新状态,下面是一个例子:

    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.setState({this.state.booksData: this.state.booksData.map(book => book.id === id ? book.quantity - 1 : book)})}>Reserve {quantity}</button>
                      <span>{this.state.quantity}</span>
                    </div>
                    );
                })
                }
              </div>
            )
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      通常(从更高级别)您想要修改您的状态,以及它是如何更新的。在大多数情况下,您的initialState 有一个undefined 值,而subscriber 中的计算是使用未定义的值完成的。

      但就我而言,我在 reducer 中定义了初始状态,subscriber 具有默认值(最初),但在 componentDidUpdate 中调度了一个动作(来自早期的重新渲染之一) publisher) 会将上述值重新分配给 undefined (因此在控制台中会引发警告)。但是,稍后的重新渲染(当网络请求成功时)会派发一个动作以重新分配一个实际值!

      混乱的状态管理,但你明白了!我所做的是为特定字段添加prevStatethis.state 的相等性检查,错误得到解决。后来我改进了状态管理来避免这种复杂性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 2015-01-15
        • 2016-05-24
        • 1970-01-01
        相关资源
        最近更新 更多