- 定义
export default class StateComponent extends React.Componnet {constructor(props) {super(props)this.state = {count:1}}increase() {let count = this.state.count + 1this.setState({count})}decrease = () => {let count = this.state.count - 1this.setState({count}, () => {console.log('之后执行')})}render() {return (<div><p>{ this.state.count }</p><button onClick={ this.increase.bind(this) }>增加</button><button onClick={ this.decrease }>减少</button></div>)}}
- 不像vue, 没有初始值不能鉴听, 直接赋值 state 的变量就会 渲染页面 ```javascript
export default class StateDemo extends React.Component {
constructor(props) { super(props) this.state = {
}
} componentDidMount() { this.setState({ count: 123 }) } render() { return (
setState是同步还是异步
{this.state.count}
- 修改元素是setState, **同步还是异步?****setState会引起 页面重绘**<br />**```javascriptincrease = async () =>{// this.setState({// count: ~~(Math.random()*100)// })await this.setStateAsync({count: ~~(Math.random()*100)})console.log(this.state.count) // 实时同步}// 1. 可以用setState第二个参数 回调实时同步// 2. 自定义 promisesetStateAsync (state) {return new Promise((resolve) => {this.setState(state, resolve)})}
