We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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,同样设计深浅拷贝的问题。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
从控制台的输出中,可以看到嵌套的属性对象是整个替换原对象的, 所以丢失了属性,如果不想丢失我们必须复制整个对象,再单独修改复制对象某个属性的值,再setState的时候传入这个对象,这样做势必造成代码冗余以及深浅拷贝的问题,所以在实践中首先应尽量避免嵌套对象的出现。
如果必须出现嵌套对象,可以使用redux,因为在reducer中可以直接使用对象属性赋值的方式修改state,和setState方法不同,但一般不这样做,因为这样会改变原state,一般实践中还是要拷贝出一个新state,同样设计深浅拷贝的问题。
The text was updated successfully, but these errors were encountered: