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}

);} }

相关内容

热门资讯

塔如笔、亭似墨、池若砚、地作纸... 我一直觉得,有些地方的美是需要静下心来细细品味的,比如“易罗池”,就是这样的一处秘境。说起来也实属有...
原创 咕... 要说寒冬里最暖身的一碗汤,酸辣汤必须占有一席之地。它看似平平无奇,却是无数人的治愈系美食,三两下就能...
淮南八公山豆腐脑!安徽非遗美食... 淮南八公山豆腐脑,是镌刻着安徽非遗印记的传统美食,更是淮南人刻在骨子里的早餐标配。它承载着两千多年的...
武汉2026江西小炒论坛贺华平... 华平传媒创始人、江西省赣菜产业发展促进会副会长贺华平在2026江西小炒论坛发表《未来三年江西菜的发展...
帝寒金温|李东垣《脾胃论》80... “脾胃不好,天天喝粥养一养”“胃不舒服,喝点粥就好”——这句话,很多人从小听到大。 不少人一提到养脾...