forEach和数组的setState

时间:2017-12-22 07:19:53

标签: javascript reactjs

我打印现有的状态,比如console.log(this.state)我有

{'abc-sorted':false, 'def-sorted': 'asc', 'someotherstuff-sorted': true, show: true}

我想要做的是设置以状态键'-sorted'结尾的所有状态,我该怎么办?

我做了这个'丑陋'的事情。

Object.keys(this.state).filter(o=>{
                return o.endsWith('sorted') 
            }).forEach(o2 => {
                this.setState({
                    [o2]: false
                })
            })

除此之外的其他选择?这导致了不必要的渲染。

4 个答案:

答案 0 :(得分:4)

尝试先生成一个对象。然后设置你的状态。这样您只需设置一次。

const newState = {};

Object.keys(this.state).forEach(key => {
    if (key.endsWith('sorted')) {
      newState[key] = false;
    }
});

this.setState(newState);

答案 1 :(得分:1)

您可以在循环中调用setState而不是一次调用

const stateUpdates = {};
Object.keys(this.state).filter(o=>{
                return o.endsWith('sorted') 
            }).forEach(o2 => {
                stateUpdates[o2] = false
            })
this.setState(stateUpdates)

答案 2 :(得分:0)

您还可以使用Array.prototype.reduce()并防止州内的不变性:

const state = {
  'abc-sorted': false,
  'def-sorted': 'asc',
  'someotherstuff-sorted': true,
  show: true,
}

const containsSorted = key => key.indexOf('-sorted') !== -1

const result = Object.keys(state).reduce((prev, curr) => {
  return {
    ...prev,
    [curr]: containsSorted(curr) ? false : state[curr],
  }
}, {})

console.log(result)
// this.setState(result)

答案 3 :(得分:-1)

我希望这对您有用...

我的案例快照是对象。在我的构造函数内部

someProperty

我做到了

  this.state = {
    docs: []
  }