第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

React JS:將嵌套對(duì)象的所有值設(shè)置為 false,除了一個(gè)

React JS:將嵌套對(duì)象的所有值設(shè)置為 false,除了一個(gè)

夢(mèng)里花落0921 2023-06-15 17:46:08
我的組件具有以下?tīng)顟B(tài):this.state = {  models: {    model1: false,    model2: true,    model3: false,    model4: false  },  state1: 'somevalue',  state2: 5,  state3: false}當(dāng)onButtonClick()函數(shù)被調(diào)用時(shí),我希望所有的值this.state.models都是false除變量對(duì)應(yīng)的值之外的所有值key:onButtonClick(e){  const key = e.target.getAttribute('model');  this.setState({   models:{     //set all states to false except for the key   }  })}我怎樣才能做到這一點(diǎn)?
查看完整描述

2 回答

?
藍(lán)山帝景

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊

如果你的瀏覽器支持 spread syntax,那么更新的對(duì)象可以通過(guò)該語(yǔ)法和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)

}


查看完整回答
反對(duì) 回復(fù) 2023-06-15
?
慕婉清6462132

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊

您可以使用計(jì)算對(duì)象屬性來(lái)使其工作。this.setState進(jìn)行淺合并,您將不得不將嵌套的屬性展開(kāi)一層深。


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

   }

  })

}

如果我們想確保其他屬性始終為假,則在設(shè)置狀態(tài)之前覆蓋這些值。


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

      })

    }


查看完整回答
反對(duì) 回復(fù) 2023-06-15
  • 2 回答
  • 0 關(guān)注
  • 198 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)