【问题标题】:Decrement function in Reactjs doesn't workReactjs 中的减量函数不起作用
【发布时间】:2021-12-29 19:18:11
【问题描述】:

我在 17.02 版本中使用 ReactJs 和 React-dom。

我遇到了this question 中描述的相同问题:使用按钮递增和递减的值。我使用了建议的解决方案,更改了我以前的代码。

从这个:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità --;
        this.setState({ cards });
      }

到这个:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità = card[id].quantità > 0 ? (card[id].quantità - 1) : 0;
        this.setState({ cards });
      }

但我在控制台中看到了这个错误TypeError: Cannot read properties of undefined (reading 'quantità') 我知道意思,但我不明白为什么如果“quantità”(数量)是一个设置为零的道具,我会看到这个错误:

    state = {
        cards: [
          {id:0, nome: 'California', prezzo: 1.99, immagine: california, quantità:0},
          {id:1, nome: 'Dragon', prezzo: 3.49, immagine: dragon, quantità:0},
          {id:2, nome: 'Dynamite', prezzo: 2.49, immagine: dynamite, quantità:0},
          {id:3, nome:'Philadelphia', prezzo:0.99, immagine: philadelphia, quantità:0},
          {id:4, nome:'Rainbow', prezzo:2.99, immagine: rainbow, quantità:0},
          {id:5, nome:'Shrimp', prezzo:1.49, immagine: shrimp, quantità:0}
        ]
      }

【问题讨论】:

    标签: javascript reactjs event-handling


    【解决方案1】:

    您没有在handleDecrement 中显示对card 的引用来自何处,但在某处引用已更改,因此它在indexOf 中不起作用。相反,创建一个新列表并避免使用突变。

    handleDecrement = card => {
      const cards = this.state.cards.map(c => c.id === card.id 
        ? {...c, quantità: Math.max(0, c.quantità - 1)} 
        : c);
    
      this.setState({ cards });
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2020-04-12
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多