为什么在更新处理程序中更新其他对象的反应时setState



在Onchange事件处理程序中,我只是在usertxt上进行setState()调用,但看起来它也设置了颜色对象的状态。对我来说,奇怪的是,这仅发生在颜色对象上,而不是对年龄变量的发生。

想知道是否有人可以解释为什么会发生这种情况?这是我的webpackbin示例的链接。在输入中写入时,状态在颜色对象上更改。

我希望有人可以向我解释为什么会发生这种情况的机制。非常感谢您。

import React, { Component } from 'react';
export default class Hello extends Component {
  constructor() {
    super();
    this.handleMe = this.handleMe.bind(this);
    this.state = {
        age: 21,
        colors: {
            best: 'blue',
            second: 'green'
        },
        userTxt: ""
    }
  }
  handleMe(e) {
        let myAge = this.state.age;
        let myColors = this.state.colors;
        myAge = myAge + 1;
        myColors['best'] = 'mistyrose';
        myColors['second'] = 'red';
        this.setState({ userTxt: e.target.value });
    }
  render() {
    const { age, colors, userTxt} = this.state;
    return (
      <div>
        <form action="">
          <input type="text"onChange={this.handleMe}/>
          <div>Age: {age}</div>
          <div>Colors - best: {colors.best}</div>
          <div>Colors - second: {colors.second}</div>
          <div>UserTxt: {userTxt}</div>
        </form>
      </div>
    )
  }
}[enter link description here][1]

  [1]: https://www.webpackbin.com/bins/-KvFx-s7PpQMxLH0kg7m

状态中的颜色字段是作为参考存储的对象。年龄字段是一个整数,被存储为原始值。

当您将颜色字段分配给MyColors时,两个变量都会引用同一对象。因此,当您更新MyColors时,该州的颜色字段会更新。

当您将年龄字段分配给Myage时,它将状态年龄字段的价值复制到Myage字段。因此,当您更新myage时,它不会更新状态。

在原始值与参考值

上有关此信息的更多信息

为了防止这种意外的副作用,您应该创建一个新对象并将颜色值从状态复制到它。您可以使用

来做到这一点

let myColors = {...this.state.colors};

声明变量时。

这是因为您直接在此处操纵状态了。Mycolors是指该州的颜色对象。

  handleMe(e) {
        let myAge = this.state.age;
        let myColors = this.state.colors;
        myAge = myAge + 1;
        //directly mutating the state with these 2 lines.
        myColors['best'] = 'mistyrose';
        myColors['second'] = 'red';
        this.setState({ userTxt: e.target.value });
    }

您需要复制this.state.colors,例如让mycolors = object.assign({},this.state.colors)

最新更新