React之组件state的正确打开方式
发布时间:2020-12-15 07:14:04 所属栏目:百科 来源:网络整理
导读:setState是改变React组件中state值的唯一方法,不能直接对state赋值: class Dog extends Component { constructor(props) { super(props) this.state = { color: 'white',age: 7,son: { color: 'gray',age: 1 } } } brushHair() { //right setState({color:
setState是改变React组件中state值的唯一方法,不能直接对state赋值:class Dog extends Component { constructor(props) { super(props) this.state = { color: 'white',age: 7,son: { color: 'gray',age: 1 } } } brushHair() { //right setState({color: 'black'}) //wrong this.state.color = 'black'; } } state的更新可能是异步的,不要依赖当前state的值去计算下一个stateaddAge() { //wrong setState({age: ++this.state.age}) }
当更新state的部分属性时,其他属性是不会受影响的,但仅限于第一层结构brushSonHair() { setState({ son: { color: 'black' } }) }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |