为了账号安全,请及时绑定邮箱和手机立即绑定

React:如何在数组映射中更新对象

React:如何在数组映射中更新对象

明月笑刀无情 2019-04-24 19:15:05
我正在尝试在单击按钮时更新数组的值。但我无法弄清楚如何使用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单击按钮时如何递增?
查看完整描述

6 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

您可以拥有一个处理程序,用于映射counters和更新单击按钮的相应计数器项。这里我们i从父作用域中取出,并比较它以找到要更改的正确项目。

<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>


查看完整回答
反对 回复 2019-05-17
?
Helenr

TA贡献1780条经验 获得超4个赞

您可以创建这样的单击处理程序

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)}>

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


查看完整回答
反对 回复 2019-05-17
?
慕勒3428872

TA贡献1848条经验 获得超6个赞

您可以使用i已有的将计数器映射到新数组,用更新的计数替换目标项:


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


查看完整回答
反对 回复 2019-05-17
  • 6 回答
  • 0 关注
  • 1169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信