【问题标题】:update object key in react array state [duplicate]更新反应数组状态中的对象键[重复]
【发布时间】:2018-09-18 03:58:39
【问题描述】:

为什么这很难做到或找到答案?

我有我的状态

state: {
   people: [
     {name: 'tom'},
     {name: 'rich'},
   ]
}

为什么把 Tom 改成 Pete 就这么难?

const people = this.state.people.slice();
people[i].name = value;
this.setState({ people });

我可以这样做,但 1) i 未定义,2) 看起来很乱

有没有更优雅的方法来更新对象键??

【问题讨论】:

  • 我也想问i,你有要求更新所有名字还是某个索引?
  • 当我点击它时只需要更新该特定记录的名称

标签: javascript reactjs object state


【解决方案1】:

如果您尝试重命名第一个元素,您需要传递整数索引:

const people = this.state.people.slice();
people[0].name = value;
this.setState({ people });

如果您需要重命名由name tom 指定的元素,例如使用 es6 .findIndex 方法:

const people = this.state.people.slice();
const index = people.findIndex(item => item.name === 'tom');
if(index >= 0) {
  people[index].name = value;
}
this.setState({ people });

【讨论】:

    【解决方案2】:

    你没有循环任何东西,所以是的 i 是未定义的。

    假设您有一个项目的点击处理程序..

    {this.state.people.map( (person, idx) => <div onClick={this.handleClick.bind(this, idx)>Person here!</div>)}
    

    现在从这里你有一个索引来更新记录...

    然后你的人更新你可以在句柄函数const person = {...this.state.people[idx]}

    请注意,我在这里为该人创建了一个新对象,因此确保不会直接改变状态对象。假设您在某处有另一个值或状态变量,您可以将该值分配给该人

    编辑:

    handleClick = (idx, e) => {
        const { value } = e.target;
        const robots = [].concat(this.state.robots);
        const robot = robots[idx]
        robot.name = value;
        robots[idx] = robot;
        this.setState({robots})
    }
    

    【讨论】:

    • 我很困惑。你的方法有效,但我仍然收到错误说cant read e of undefined updateRobotName = (index) =&gt; { const { value, name } = e.target; //the e here const newRobot = {...this.state.robots[index]} } 但是当我删除这条线时,它就不起作用了?当我将e 传递给函数时,它仍然不起作用??
    • 我很乐意提供帮助,但我需要查看代码或更多正在发生的事情才能给出一个好的/正确的答案
    • 好的,约翰,试试这个:codesandbox.io/s/x9q84po70o。我将如何更新该州的这些名称?
    • @TheWalrus 好酷,是的,你只需要改变机器人对象,分配给机器人数组并将其设置为状态。我为数组创建了一个新的对象签名,这样你就不会直接改变状态。看到这里codesandbox.io/s/olwwj0xmw9 ....如果您还有任何问题,请不要犹豫! :)
    【解决方案3】:

    假设你在 JSX 中打印名字如下

    const { people } = this.state;
    return people.map((person, index) => {
        <p
            onClick={() => {
                const newPeople = people.slice();
                newPeople[index] = 'some calculation to find new name';
                this.setState({ people: newPeople });
            }}
        >
            {person.name}
        </p>
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2018-04-04
      • 2017-08-08
      • 2019-11-08
      • 1970-01-01
      相关资源
      最近更新 更多