React - setState 更新状态的两种写法
- 一.对象式的 setState
- 二. 函数式的 setState
- 三. 对象式的setState 对比 函数式的 setState
- 四. 一个 setState 使用组件实例
setState()
将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。setState()
并不总是立即更新组件,它会批量推迟更新(异步执行)。
一.对象式的 setState
setState(stateChange, [callback])
stateChange
:为状态改变对象(该对象可以体现出状态的更改)callback
是可选的回调函数, 它在状态更新完毕、界面也更新后(render()
调用后)才会被调用
- 不使用回调函数
this.setState({ count: 10 });
- 使用回调函数
this.setState({count: 10,},() => {console.log('render()渲染之后', this.state.count);}
);
二. 函数式的 setState
setState(updater, [callback])
updater
:
(1)返回 stateChange
对象的函数
(2)可以接收到两个参数:state
(当前组件的state)和 props
(组件外部传递过来的参数)callback
是可选的回调函数, 它在状态更新完毕、界面也更新后(render()
调用后)才会被调用
- 不使用回调函数
this.setState((state, props) => {console.log(state, props);return { count: 10 };
});
- 使用回调函数
this.setState((state, props) => {console.log(state, props);return { count: 10 };},() => {console.log('render()渲染之后', this.state.count);}
);
三. 对象式的setState 对比 函数式的 setState
对象式的setState
是函数式的setState
的简写方式(语法糖)
- 如果 新状态 不依赖于 原状态 ,推荐使用
对象方式
- 如果 新状态 依赖于 原状态 ,推荐使用
函数方式
- 如果需要在 setState()执行后 获取最新的状态数据,要在第二个
callback
函数中读取
四. 一个 setState 使用组件实例
import React, { Component } from "react";export default class index extends Component {state = {count: 0,};increment1 = () => {this.setState({count: this.state.count + 1,},() => {console.log(222, this.state.count);});console.log(111, this.state.count);};increment2 = () => {this.setState((state, props) => {console.log(state, props);return { count: state.count + 2 };},() => {console.log(222, this.state.count);});console.log(111, this.state.count);};render() {return (<div><h4>数值为:{this.state.count}</h4><button onClick={this.increment1}>+1</button><button onClick={this.increment2}>+2</button></div>);}
}