2017-09-30 3 views
0

onChangeイベントハンドラでは、userTxtに対してsetState()を呼び出すだけですが、カラーオブジェクトの状態も設定されているように見えます。私にとって奇妙なことは、これは色オブジェクトに対してのみ起こりますが、年齢変数には起こらないということです。SetStateがハンドラ内の他のオブジェクトの更新に反応しているのはなぜですか?

誰かがなぜこれが起こっているのか説明できますか? Here is a link to my webpackbin example. As you write in the input, the state is changed on the color object.

私は、誰かがなぜこれが起こっているのかのメカニズムを私に説明してくれることを願っていました。事前にどうもありがとうございました。

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 

答えて

1

状態の色フィールドが対象であるmyColors = Object.assign({}、this.state.colors)とするようなthis.state.colorsのコピーを作成する必要があります基準として記憶される。 ageフィールドは整数であり、プリミティブ値として格納されます。

myColorsにカラーフィールドを割り当てると、両方の変数が同じオブジェクトを参照します。したがって、myColorsを更新すると、状態のcolorsフィールドが更新されます。

ageフィールドをmyAgeに割り当てると、ageフィールドの値がmyAgeフィールドにコピーされます。したがって、myAgeを更新すると、状態は更新されません。この予期せぬ副作用を防ぐためにPrimitive value vs Reference value

でこの上

より、新しいオブジェクトを作成して状態から色の値をコピーする必要があります。あなたは、変数を宣言するとき

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

を使用してこれを行うことができます。

1

これは、ここで状態を直接操作しているために発生しています。 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 }); 
    } 

あなたは

関連する問題