如何将新对象作为值添加到处于反应状态的数组中

时间:2017-10-04 06:54:33

标签: javascript arrays reactjs

我想在react状态下为数组添加一个新值,但是我一直遇到错误,有人可以指导我解决这个问题吗?

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 个答案:

答案 0 :(得分:0)

您必须绑定addItem函数才能使用“this”而不会出错。

有两种方式:

1 /词法绑定:(使用“=>”)

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

2 /在构造函数中绑定:

  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);
  }