Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【React setState时处理嵌套的对象】 #60

Open
kind-hearted opened this issue Oct 9, 2018 · 0 comments
Open

【React setState时处理嵌套的对象】 #60

kind-hearted opened this issue Oct 9, 2018 · 0 comments

Comments

@kind-hearted
Copy link
Owner

kind-hearted commented Oct 9, 2018

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  state = {
    number: 0,
    nested: {
      name: 'world',
      text: 'hello'
    }
  }

  changeNumber = () => {
    this.setState({
      number: this.state.number + 1
    }, function () {
      console.log(JSON.stringify(this.state, null, '  '))
      // {
      //   "number": 1,
      //     "nested": {
      //     "name": "world",
      //       "text": "hello"
      //   }
      // }
    })
  }

  changeName = () => {
    this.setState({
      nested: {
        name: 'world1'
      }
    }, function () {
      console.log(JSON.stringify(this.state, null, '  '))
      // {
      //   "number": 1,
      //     "nested": {
      //     "name": "world1"
      //   }
      // }
    })
  }

  changeText = () => {
    this.setState({
      nested: {
        text: 'hello1'
      }
    }, function () {
      console.log(JSON.stringify(this.state, null, '  '))
      // {
      //   "number": 2,
      //     "nested": {
      //     "text": "hello1"
      //   }
      // }
    })
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
        </header>
        <p>{this.state.number}</p>
        <button type="button" onClick={this.changeNumber}>changeNumber</button>
        <p>{this.state.nested.name}</p>
        <button type="button" onClick={this.changeName}>changeName</button>
        <p>{this.state.nested.text}</p>
        <button type="button" onClick={this.changeText}>changeText</button>
      </div>
    );
  }
}

export default App;

从控制台的输出中,可以看到嵌套的属性对象是整个替换原对象的, 所以丢失了属性,如果不想丢失我们必须复制整个对象,再单独修改复制对象某个属性的值,再setState的时候传入这个对象,这样做势必造成代码冗余以及深浅拷贝的问题,所以在实践中首先应尽量避免嵌套对象的出现。

如果必须出现嵌套对象,可以使用redux,因为在reducer中可以直接使用对象属性赋值的方式修改state,和setState方法不同,但一般不这样做,因为这样会改变原state,一般实践中还是要拷贝出一个新state,同样设计深浅拷贝的问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant