【问题标题】:Updating state with immutability helper update使用不变性帮助程序更新更新状态
【发布时间】:2017-01-29 22:10:34
【问题描述】:

我想用 immutability-helper 函数更新我的状态 update (https://github.com/kolodny/immutability-helper)

state = {
    field: '',
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
  };

addElementToList() {
 const i = this.state.items.length;
 const newState = ()=> {
  update(this.state,
    {
      items: {
        $push: [
          {
            [i]: this.state.field
          }
        ]
      }
     }
   )
 };
 this.setState = newState;
}

很遗憾,函数执行时出现以下错误。

Uncaught TypeError: (0 , _immutabilityHelper.update) is not a function

我错过了什么,对此有什么想法吗?

【问题讨论】:

  • 仅使用 JavaScript 的 Array.prototype.concat(或扩展语法)和 Array.prototype.slice 在不发生突变的情况下从数组中添加/删除元素不是更容易吗?

标签: javascript reactjs immutability


【解决方案1】:

我知道 OP 要求提供有关使用此第 3 方库的答案,但此库的原始代码 sn-p 生成的代码具有类似于回调地狱的 审美:特别是使用很多嵌套大括号花括号。

因此,我只是想权衡一下如何使用 JavaScript 的 Array.prototype.concat 来实现相同的未变异状态。

可能会发现以下方法更简洁。

使用 Array.prototype.concat:

addElementToList() {
  const i = this.state.items.length;
  const   newState = ()=> { 
    items: this.state.items.concat([this.state.field]);
  }
  this.setState = newState;
}

使用 ES6 扩展语法:

addElementToList() {
  const i = this.state.items.length;
  const   newState = ()=> { 
    items: [...this.state.items, this.state.field];
  }
  this.setState = newState;
}

原始OP代码sn-p对比:

它使用不变性帮助库 (https://github.com/kolodny/immutability-helper)

addElementToList() {
  const i = this.state.items.length;
  const newState = ()=> {
    update(this.state,
      {
         items: {
           $push: [
              {
                 [i]: this.state.field
              }
           ]
        }
      }
    )
  };
  this.setState = newState;
}

【讨论】:

  • 谢谢,传播运算符为我工作。看起来也干净了很多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2019-01-10
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多