0

I would like to add a new value to the array within the react state, but I have encountered errors along the way, could anyone guide me with the solution?

class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          Items: [
            {w:1, b:8, name: 'banana'},
            {w:7, b:3, name:'apple'},
            {w:3, b:5, name:'kiwi'},
            {w:6, b:3, name:'strawberry'},
            {w:5, b:1, name:'orange'}]
        };
      }

    addItem(weight, benefit, itemName){
      this.setState(prevState => ({
        Items: [...prevState.Items, {w:weight, b:benefit, name: itemName}]
      }))
    }

1 Answers1

0

You must bind the addItem function in order to use "this" without error.

There are 2 ways:

1/ Lexical binding: (using "=>")

addItem = (weight, benefit, itemName) => {
  this.setState(prevState => ({
    Items: [...prevState.Items, {w:weight, b:benefit, name: itemName}]
  }))
}

2/ Binding in constructor:

  constructor(props) {
    super(props);
    this.state = {
      Items: [
        {w:1, b:8, name: 'banana'},
        {w:7, b:3, name:'apple'},
        {w:3, b:5, name:'kiwi'},
        {w:6, b:3, name:'strawberry'},
        {w:5, b:1, name:'orange'}]
    };
    this.addItem = this.addItem.bind(this);
  }
thinhvo0108
  • 2,212
  • 1
  • 13
  • 23