ReactJS - Array中Object键的setState [英] ReactJS - setState of Object key in Array

查看:68
本文介绍了ReactJS - Array中Object键的setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在研究这个问题,并认为最好重构我的代码,以便将状态设置为一个对象数组。我想要做的是按一下按钮增加一个数字。

So i've been working on this for awhile and felt it would be best to refactor my code so that the state is set up as an array of objects. What i'm trying to do is increment a number on a button click.

我在一个组件中有一个回调函数,它触发一个函数来更新状态...但是我很难在对象中定位键值。

I have a callback function in a component that triggers a function to update the state...however i'm having difficulty targeting the key value within the object.

我的初始状态如下所示:

My initial state looks like this:

getInitialState: function() {
    return {
      items: [
        {
          links: 'zest',
          trackId: 1023,
          songTitle: 'z know the others',
          artist: 'zuvet',
          upVotes: 0
        },
        {
          links: 'alpha',
          trackId: 987,
          songTitle: 'ass',
          artist: 'arme',
          upVotes: 3
        },
      ]
    }

我试图定位 upVotes 键,但无法弄清楚如何。我的函数传递一个键,以便我可以在数组中定位索引,但是当我尝试执行以下操作时: this.setState({items [key]:{upVotes:this.state.items [ key] .upVotes + 1}})由于意外的 [令牌,它会引发错误。

I am trying to target the upVotes key, but can't figure out how. My function passes a key so that I can target the index in the array, but when I try to do something like: this.setState({items[key]: {upVotes: this.state.items[key].upVotes + 1}}) it throws an error due to the unexpected [ token.

我尝试过类似这个线程的东西 here ,但我不断收到错误。

I have tried something similar to this thread here, but I keep getting errors.

我可以写什么样的函数来设置我想要定位的对象中的键的状态?

What kind of function can I write that will setState of just the key in the object that I want to target?

推荐答案

获取当前状态,修改它并 setState()它:

Get current state, modify it and setState() it:

var stateCopy = Object.assign({}, this.state);
stateCopy.items[key].upVotes += 1;
this.setState(stateCopy);

注意:这会改变状态。以下是没有变异的方法:

Note: This will mutate the state. Here's how to do it without mutation:

var stateCopy = Object.assign({}, this.state);
stateCopy.items = stateCopy.items.slice();
stateCopy.items[key] = Object.assign({}, stateCopy.items[key]);
stateCopy.items[key].upVotes += 1;
this.setState(stateCopy);

这篇关于ReactJS - Array中Object键的setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆