正确使用setState

2020-08-28  本文已影响0人  湾湾_moon

1、参数

setState(partialState,callback)
partialState:object|function

用于产生与当前state合并的子集

callback

state更新后立即执行的回调函数

2、setState更新(异步更新、同步更新)

在合成事件中异步更新

import React, { Component } from 'react'

export default class test extends Component {
    constructor(props) {
        super(props)
        this.state = {
            num: 0
        }
    }
    changeNumInner = () => {
        this.setState({
            num: this.state.num + 1
        })
        console.log('this.state.num', this.state.num)
    }
    changeNum = () => {
        this.changeNumInner()
    }

    render() {
        const { num } = this.state
        return (
            <div>
                <button onClick={this.changeNum}>{num}</button>
            </div>
        )
    }
}

在setTimeout中同步更新

changeNum = () => {
    setTimeout(() => {
        this.changeNumInner()
    }, 0)
}

在原生事件中同步更新

componentDidMount() {
    const ele = document.getElementById('xx')
    ele.addEventListener('click', this.changeNumInner, false)
}

利用setState第二个callback参数同步更新

changeNumInner = () => {
    this.setState({
        num: this.state.num + 1
    }, () => {
        console.log('立即拿到state最新值', this.state.num)
    })  
}

利用setState第二个callback参数同步更新

changeNumInner = () => {
    this.setState({
        num: this.state.num + 1
    }, () => {
        console.log('立即拿到state最新值', this.state.num)
    })  
}

State 的更新会被合并

changeNumInner = () => {
    this.setState({ num: this.state.num + 1 })
}

changeNum = () => {
    this.changeNumInner()
    this.changeNumInner()
}

实现State的链式调用

changeNumInner = () => {
    this.setState((prevState) => ({
        num: prevState.num + 1
    }))
}
上一篇 下一篇

猜你喜欢

热点阅读