网站布局有哪些常见的,服务器 网站建设,湖北营销型网站建设,钢铁网站建设1.setState
setState更新状态的2种写法#xff08;1#xff09;.setState(stateChange,[callback])----对象式的setState1.stateChange为状态改变对象#xff08;该对象可以体现出状态的更改#xff09;2.callback是可选的回调函数#xff0c;它在状态更新完毕、界面也更新… 1.setState
setState更新状态的2种写法1.setState(stateChange,[callback])----对象式的setState1.stateChange为状态改变对象该对象可以体现出状态的更改2.callback是可选的回调函数它在状态更新完毕、界面也更新后render调用后才被调用2.setState(updater,[callback])----函数式的setState1.updater为返回stateChange对象的函数2.updater可以接收到state和props3.callback是可选的回调函数它在状态更新界面也更新后render调用后才被调用。总结1.对象式的setState是函数式的setState的简写方式语法糖2.使用原则(a).如果新状态不依赖于原状态 使用对象方式(b).如果新状态依赖于原状态 使用函数方式(c).如果需要在setState()执行后获取最新的状态数据要在第二个callback函数中读取3.举个例子// a不依赖于原状态// 函数式的setStatethis.setState(()({count:99}))// 对象式的setState this.setState({count:99}) import React, {Component} from react;export default class Demo extends Component {state {count:0}add () {/*// 对象式的 setState// 1.获取原来的值const {count} this.state//2.更新状态this.setState({count:count1},(){console.log(before count:,count)console.log(after this.state.count:,this.state.count)})*/// 函数式的setState 传入两个参数// this.setState((state,props){// console.log(state,props:,state, props)// return {count:state.count1}// })// 函数式的setState 传入一个参数// this.setState(state ({count:state.count1}))// 对象式的setStatethis.setState({count:this.state.count1})}render() {return (divh1当前求和为:{this.state.count}/h1button onClick{this.add}功德1/button/div);}
};