在Reactjs中设置嵌套对象状态的正确方法是什么?

此代码段从我目前在这家X公司工作的软件中复制了我的问题。


import React, { Component } from 'react';

import { render } from 'react-dom';

import Hello from './Hello';

import './style.css';


class App extends Component {

  constructor() {

    super();

    this.state = {

      name: 'React',

      some:{

        name:"axys",

        a:[1,2.23,46,612,5],

        z:{

          a:2,

          b:5,

          c:6,

        }

      }

    };

  }


handler = () =>{

  console.log(this.state);

  this.setState({

    some:{

      z:{

        a:1111

      }

    }

  },()=>{

    console.log(this.state);

  })

}


  render() {

    return (

      <div>

        <Hello name={this.state.name} />

        <button onClick = {this.handler}>

          Change State

        </button>

      </div>

    );

  }

}


render(<App />, document.getElementById('root'));


可以说我想更改this.state.some.za的值,尽管我最初是


this.setState({

    some:{

      z:{

        a:1111

      }

    }

}

但是事实证明,返回给我的状态是


{

  "name": "React",

  "some": {

    "z": {

      "a": 1111

    }

  }

}

因此,要获得预期的输出,我需要编写


this.setState({

    some:{

      ...this.state.some,

      z:{

        ...this.state.some.z,

        a:1111

      }

    }

  }

所以我的问题是,这是正确/推荐的做事方式还是我错过了什么。


如果这是正确的方法,则setState的性能是否不依赖于Spread Operator(...)?


白猪掌柜的
浏览 203回答 2
2回答

肥皂起泡泡

there are two ways to do it&nbsp;1. copy the object into some:&nbsp; &nbsp; handler = () => {&nbsp; &nbsp; &nbsp; &nbsp; let some = Object.assign({}, this.state.some);&nbsp; &nbsp; &nbsp; &nbsp; some.z.a = 1111;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ some }, () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; };will give an output:&nbsp; &nbsp; {&nbsp; &nbsp; name: "React"&nbsp; &nbsp; some: Object&nbsp; &nbsp; name: "axys"&nbsp; &nbsp; a: Array[5]&nbsp; &nbsp; z: Object&nbsp; &nbsp; a: 1111&nbsp; &nbsp; b: 5&nbsp; &nbsp; c: 6}2. using the spead oprator&nbsp; &nbsp; handler = () => {&nbsp; &nbsp; &nbsp; &nbsp; let some = { ...this.state.some };&nbsp; &nbsp; &nbsp; &nbsp; console.log(some)&nbsp; &nbsp; &nbsp; &nbsp; this.setState(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prevstate => ({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; some: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;z:{ ...prevstate.some.z,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a: 1111}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; };with solution:&nbsp; &nbsp; {name: "React"&nbsp; &nbsp; some: Object&nbsp; &nbsp; z: Object&nbsp; &nbsp; a: 1111&nbsp; &nbsp; b: 5&nbsp; &nbsp; c: 6}hope it will help
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript