• React---新扩展setState和lazyLoad


    一、setState

    1. setState更新状态的2种写法

        (1). setState(stateChange[callback])------对象式的setState
                1.stateChange为状态改变对象(该对象可以体现出状态的更改)
                2.callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用
                        
        (2). setState(updater, [callback])------函数式的setState
                1.updater为返回stateChange对象的函数。
                2.updater可以接收到stateprops
                4.callback是可选的回调函数, 它在状态更新、界面也更新后(render调用后)才被调用。
    总结:
            1.对象式的setState是函数式的setState的简写方式(语法糖)
            2.使用原则:
                    (1).如果新状态不依赖于原状态 ===> 使用对象方式
                    (2).如果新状态依赖于原状态 ===> 使用函数方式
                    (3).如果需要在setState()执行后获取最新的状态数据, 
                        要在第二个callback函数中读取

    2.代码

     1 import React, { Component } from 'react'
     2 
     3 export default class Demo extends Component {
     4 
     5     state = {count:0}
     6 
     7     add = ()=>{
     8         //对象式的setState
     9         /* //1.获取原来的count值
    10         const {count} = this.state
    11         //2.更新状态
    12         this.setState({count:count+1},()=>{
    13             console.log(this.state.count);
    14         })
    15         //console.log('12行的输出',this.state.count); //0 */
    16 
    17         //函数式的setState
    18         this.setState( state => ({count:state.count+1}))
    19     }
    20 
    21     render() {
    22         return (
    23             <div>
    24                 <h1>当前求和为:{this.state.count}</h1>
    25                 <button onClick={this.add}>点我+1</button>
    26             </div>
    27         )
    28     }
    29 }

    二、lazyLoad

    1. 路由组件的lazyLoad

     
        //1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
        const Login = lazy(()=>import('@/pages/Login'))
        
        //2.通过<Suspense>指定在加载得到路由打包文件前显示一个自定义loading界面
        <Suspense fallback={<h1>loading.....</h1>}>
            <Switch>
                <Route path="/xxx" component={Xxxx}/>
                <Redirect to="/login"/>
            </Switch>
        </Suspense>
     
     
     
  • 相关阅读:
    jquery 的 outerWidth() 、width() 、innerWidth()
    图片自动切换 避免 鼠标快速滑过
    Ajax中日历控件的使用
    asp.net如何读取xml文件中的数据
    ASP.NET使用AspNetPager实现简单的分页功能
    XmlDataDocument与DataSet相互转化
    C#中如何过滤掉多余的html代码
    asp.net的几种经典的页面传值方法
    ASP.Net分页方法详解
    ASP.Net中省市级联有关
  • 原文地址:https://www.cnblogs.com/le220/p/14715709.html
Copyright © 2020-2023  润新知