猿问

React JS:将嵌套对象的所有值设置为 false,除了一个

我的组件具有以下状态:


this.state = {

  models: {

    model1: false,

    model2: true,

    model3: false,

    model4: false

  },


  state1: 'somevalue',

  state2: 5,

  state3: false


}

当onButtonClick()函数被调用时,我希望所有的值this.state.models都是false除变量对应的值之外的所有值key:


onButtonClick(e){

  const key = e.target.getAttribute('model');


  this.setState({

   models:{

     //set all states to false except for the key

   }

  })

}

我怎样才能做到这一点?


梦里花落0921
浏览 181回答 2
2回答

蓝山帝景

如果你的浏览器支持 spread syntax,那么更新的对象可以通过该语法和Array#reducemodels获得,如下所述:onButtonClick(e){  const key = e.target.getAttribute('model');    // Get reference to current models object in state  const models = this.state.models;      // Compose new state object by..  const state = {     models :     Object    .keys(models) // Get list of keys in model    .reduce((result, k) => {       // Reduce keys to object of key/value pairs      // where key match is set to true      return { ...result, [k] : key === k };    }, {})  }  this.setState(state)}

慕婉清6462132

您可以使用计算对象属性来使其工作。this.setState进行浅合并,您将不得不将嵌套的属性展开一层深。onButtonClick(e){  const key = e.target.getAttribute('model');  this.setState({   models:{     // spread all the properties for models     ...this.state.models,     [key]: true // set the key prop to false   }  })}如果我们想确保其他属性始终为假,则在设置状态之前覆盖这些值。onButtonClick(e){      const key = e.target.getAttribute('model');      const updatedModels = Object.entries(this.state.models)                                  .reduce((memo, [currKey]) => {         if(currKey === key) {             memo[currKey] = true;         } else {             memo[currKey] = false;         }                  return memo;      }, {});          this.setState({       models: updatedModels      })    }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答