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

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

React:如何在數(shù)組映射中更新對(duì)象

React:如何在數(shù)組映射中更新對(duì)象

明月笑刀無情 2019-04-24 19:15:05
我正在嘗試在單擊按鈕時(shí)更新數(shù)組的值。但我無法弄清楚如何使用this.setState。export default class App extends React.Component {   state = {     counters: [{ name: "item1", value: 0 }, { name: "item2", value: 5 }]   };   render() {     return this.state.counters.map((counter, i) => {       return (         <div>           {counter.name}, {counter.value}           <button onClick={/* increment counter.value here */}>+</button>         </div>       );     });   }}counter.value單擊按鈕時(shí)如何遞增?
查看完整描述

6 回答

?
交互式愛情

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

您可以擁有一個(gè)處理程序,用于映射counters和更新單擊按鈕的相應(yīng)計(jì)數(shù)器項(xiàng)。這里我們i從父作用域中取出,并比較它以找到要更改的正確項(xiàng)目。

<button onClick={() => {
    this.setState(state => ({
        counters: state.counters.map((item, j) => {
            // is this the counter that I want to update?
            if (j === i) {
                return {
                    ...item,
                    value: item.value + 1
                }
            }
            return item
        })
    }))}}>+</button>


查看完整回答
反對(duì) 回復(fù) 2019-05-17
?
Helenr

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

您可以創(chuàng)建這樣的單擊處理程序

handleClick = (index) => {
  this.setState(state => {
    const obj = state.counters[index]; // assign the object at the index to a variable
    obj.value++; // increment the value in the object
    state.counters.splice(index, 1); // remove the object from the array
    return { counters: [...state.counters, obj] };
  });}

像這樣稱呼它...... <button onClick={() => handleClick(i)}>

可以縮短它。只是想解釋一下你如何去做


查看完整回答
反對(duì) 回復(fù) 2019-05-17
?
慕勒3428872

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

您可以使用i已有的將計(jì)數(shù)器映射到新數(shù)組,用更新的計(jì)數(shù)替換目標(biāo)項(xiàng):


  () => this.setState(({ counters }) => ({ counters: counters.map((prev, i2) => i === i2 ? { ...counter, count: counter.count + 1 } : prev) }))


查看完整回答
反對(duì) 回復(fù) 2019-05-17
  • 6 回答
  • 0 關(guān)注
  • 1188 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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