• 定义
    1. export default class StateComponent extends React.Componnet {
    2. constructor(props) {
    3. super(props)
    4. this.state = {
    5. count1
    6. }
    7. }
    8. increase() {
    9. let count = this.state.count + 1
    10. this.setState({
    11. count
    12. })
    13. }
    14. decrease = () => {
    15. let count = this.state.count - 1
    16. this.setState({
    17. count
    18. }, () => {
    19. console.log('之后执行')
    20. })
    21. }
    22. render() {
    23. return (
    24. <div>
    25. <p>{ this.state.count }</p>
    26. <button onClick={ this.increase.bind(this) }>增加</button>
    27. <button onClick={ this.decrease }>减少</button>
    28. </div>
    29. )
    30. }
    31. }
    • 不像vue, 没有初始值不能鉴听, 直接赋值 state 的变量就会 渲染页面 ```javascript

    export default class StateDemo extends React.Component {

    constructor(props) { super(props) this.state = {

    1. }

    } componentDidMount() { this.setState({ count: 123 }) } render() { return (

    setState是同步还是异步

    {this.state.count}

    ) } }

    1. - 修改元素是setState **同步还是异步?**
    2. **setState会引起 页面重绘**<br />**
    3. ```javascript
    4. increase = async () =>{
    5. // this.setState({
    6. // count: ~~(Math.random()*100)
    7. // })
    8. await this.setStateAsync({count: ~~(Math.random()*100)})
    9. console.log(this.state.count) // 实时同步
    10. }
    11. // 1. 可以用setState第二个参数 回调实时同步
    12. // 2. 自定义 promise
    13. setStateAsync (state) {
    14. return new Promise((resolve) => {
    15. this.setState(state, resolve)
    16. })
    17. }