React - setState 更新状态的两种写法
admin
2024-03-24 05:04:36

React - setState 更新状态的两种写法

  • 一.对象式的 setState
  • 二. 函数式的 setState
  • 三. 对象式的setState 对比 函数式的 setState
  • 四. 一个 setState 使用组件实例

  1. setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。
  2. setState() 并不总是立即更新组件,它会批量推迟更新(异步执行)。

一.对象式的 setState

setState(stateChange, [callback])

  • stateChange :为状态改变对象(该对象可以体现出状态的更改)
  • callback 是可选的回调函数, 它在状态更新完毕、界面也更新后(render()调用后)才会被调用
  1. 不使用回调函数
    this.setState({ count: 10 });
    
  2. 使用回调函数
    this.setState({count: 10,},() => {console.log('render()渲染之后', this.state.count);}
    );
    

二. 函数式的 setState

setState(updater, [callback])

  • updater :
    (1)返回 stateChange 对象的函数
    (2)可以接收到两个参数:state (当前组件的state)和 props(组件外部传递过来的参数)
  • callback 是可选的回调函数, 它在状态更新完毕、界面也更新后(render()调用后)才会被调用
  1. 不使用回调函数
    // state 当前组件的state
    // props 当前组件外部传递过来的参数
    this.setState((state, props) => {console.log(state, props);return { count: 10 };
    });
    
  2. 使用回调函数
    this.setState(// state 当前组件的state// props 当前组件外部传递过来的参数(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 = () => {// 对象式的setStatethis.setState({count: this.state.count + 1,},() => {console.log(222, this.state.count);});console.log(111, this.state.count);};increment2 = () => {// 函数式的setState// state 当前组件的state// props 当前组件外部传递过来的参数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 (

数值为:{this.state.count}

);} }

相关内容

热门资讯

山水皆有情!丽江两山一江的千年... 去过丽江、走过虎跳峡的人,大概率都听过哈巴雪山和金沙江的传说。很多人站在峡谷之下,望着奔腾不息的金沙...
活力中国调研行丨“殷”你而来 ... 9月12日,游客在殷墟博物馆“甲骨文展厅”内参观。位于河南省安阳市的殷墟博物馆新馆是首个全景式展现商...
浦江之夜赴美好相逢,第37届上... 9月12日晚,黄浦江畔灯火璀璨,第37届上海旅游节大巡游在外滩中山东一路上演。不少观众早早便来到外滩...
美丽中国丨秋韵紫鹊界 梯田入画... 这是9月11日拍摄的紫鹊界梯田(无人机照片)。 金秋九月,湖南省娄底市新化县紫鹊界梯田稻谷渐次成熟。...
中国之巅奏响《共同的节日》,千... 千吨阻尼器,“迎世赛、游上海旅游节”。9月13日,由上海市文化和旅游局指导推出上海旅游·会客│巅峰之...