当前位置: 首页 > React学习笔记 > 正文
流量卡

React组件进阶及生命周期

游魂 发表于2022年6月15日 11:24

props - 类型校验

// 开发者A创建的组件
const List = props => {
  const arr = props.colors
  const list = arr.map((item, index) => <li key={index}>{item.name}</li>)
    return (
        <ul>{list}</ul>
    )
}

// 开发者B去使用组件
<List colors={19} />

报错:TypeError: arr.map is not a function

import PropTypes from 'prop-types'

const List = props => {
  const arr = props.colors
  const lis = arr.map((item, index) => <li key={index}>{item.name}</li>)
  return <ul>{lis}</ul>
}

List.propTypes = {
  // props属性:校验规则
  colors: PropTypes.array
}

Props - 类型校验常见类型

常见的校验规则

  1. 常见类型:array、bool、func、number、object、string
  2. React元素类型:element
  3. 必填项:isRequired
  4. 特定结构的对象:shape({})

校验规则的使用

const Demo = (props) => {
  return <div>Demo组件</div>
}
Demo.propTypes = {
  // 常见类型
  optionalFunc: PropTypes.func,
  // 常见类型+必填
  requiredFunc: PropTypes.func.isRequired,
  // 特定结构的对象
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  })
}

props - 默认值

作用:给组件的props设置默认值,在未传入props的时候生效

设置props的默认值

// 分页组件
const Pagination = (props) => {
  return <div> pageSize的默认值:{props.pageSize}</div>
}
// 设置默认值
Pagination.defaultProps = {
    pageSize: 10
}
// 使用组件
<Pagination />

新版react推荐使用参数默认值来实现

// 分页组件
const Pagination = ({pageSize = 10}) => {
  return <div> pageSize的默认值:{pageSize}</div>
}
// 使用组件
<Pagination />

props - 静态属性写法

类的静态属性

class Person {
  // 实例属性
  gender = '男'
  // 静态属性
  static age = 18
}
// 访问静态属性
console.log(Person.age) // 18
// 访问实例属性
const p = new Person()
console.log(p.gender)   // 男

类组件中 propTypes defaultProps 的使用

class Demo extends Component {
  // 校验
  static propTypes = {
    colors: PropTypes.array,
    gender: PropTypes.oneOf(['男', '女']).isRequired
  }
  // 默认值
  static defaultProps = {
    gender: '男'
  }

  render() {
    return <div>Demo组件</div>
  }
}

生命周期 - 概览

什么是组件生命周期

人一生缩影

React类组件的生命周期整体概览,组件从创建到消耗的过程

React组件生命周期

image-20220608143938263

生命周期的意义

总结:只有类组件才有生命周期,分为 挂载阶段 更新阶段 卸载阶段

生命周期 - 挂载阶段

执行顺序

constructor() —> render() —> componentDidMount()

触发时机及作用

钩子函数 触发时机 作用
constructor 创建组件时,最先执行 1. 初始化state 2. 创建 Ref 3. 使用 bind 解决 this 指向问题等
render 每次组件渲染都会触发 渲染UI(注意: 不能调用setState()
componentDidMount 组件挂载(完成DOM渲染)后 1. 发送网络请求 2.DOM操作

例:

import { Component } from 'react'

export default class App extends Component {
  constructor () {
    super()
    console.log('1. constructor执行')
  }
  componentDidMount () {
    console.log('3. componentDidMount执行')
  }
  render() {
    console.log('2. render执行')
    return <div>App组件</div>
  }
}

生命周期 - 更新阶段

执行顺序

render() —> componentDidUpdate()

何时触发更新阶段

  1. setState()
  2. forceUpdate() 强制组件更新
  3. 组件接收到新的props(实际上,只需要父组件更新,子组件就会重新渲染)

触发时机及作用

钩子函数 触发时机 作用
render 每次组件渲染都会触发 渲染UI(与 挂载阶段 是同一个render)
componentDidUpdate 组件更新(完成DOM渲染)后 DOM操作,可以获取到更新后的DOM内容,不要直接调用setState

例:

import { Component } from 'react'

class Child extends Component {
  render() {
    return <h1>统计豆豆被打的次数:</h1>
  }
}

export default class App extends Component {
  state = {
    count: 0
  }

    handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  componentDidUpdate() {
    console.log('2. componentDidUpdate执行')
  }

  render() {
    console.log('1. render执行')
    return (
      <div>
        <Child />
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

生命周期 - 卸载阶段

什么时候触发卸载?

触发时机及作用

钩子函数 触发时机 作用
componentWillUnmount 组件卸载(从页面中消失) 执行清理工作(比如:清理定时器等)

例:

import { Component } from 'react'

class Child extends Component {
  componentWillUnmount () {
    console.log('componentWillUnmount执行')
  }
  render() {
    return <h1>统计豆豆被打的次数:{this.props.count}</h1>
  }
}

export default class App extends Component {
  state = {
    count: 0
  }

    handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    return (
      <div>
        { this.state.count < 5 && <Child count={this.state.count} />}
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

setState扩展 - 发现问题

发现setState是“异步”的,多次setState会合并。

import React, {Component} from 'react' 
export default class Demo extends Component {
  state = {
    count: 0
  }
  handleClick = () => {
    this.setState({count: this.state.count+100})
    this.setState({count: this.state.count+1})
    console.log(this.state.count)  // 打印0
  }
  render() {
    console.log('render')
    return (
      <div>
        <div>Demo组件:{this.state.count}</div>
        <button onClick={this.handleClick}>体现“异步”和合并</button> 
      </div>
    )
  }
}

setState扩展 - 更多用法

import React, {Component} from 'react' 
export default class Demo extends Component {
  state = {
    count: 0
  }
  handleClick = () => {
    // this.setState({count: this.state.count+1})
    // this.setState({count: this.state.count+1})
    // this.setState({count: this.state.count+1})
    // 页面展示 1
    this.setState(prevState=>{
      return {
        count: prevState.count + 1
      }
    })
    this.setState(prevState=>{
      return {
        count: prevState.count + 1
      }
    })
    this.setState(prevState=>{
      return {
        count: prevState.count + 1
      }
    })
    // 页面展示 3
  }
  render() {
    return (
      <div>
        <div>Demo组件:{this.state.count}</div>
        <button onClick={this.handleClick}>setState串联更新数据</button> 
      </div>
    )
  }
}
import React, {Component} from 'react' 
export default class Demo extends Component {
  state = {
    count: 0
  }
  handleClick = () => {
    this.setState(prevState=>{
      return {
        count: prevState.count + 1
      }
    },()=>{
       console.log('更新后:', this.state.count)  // 打印:1
    })
    console.log('未更新:', this.state.count)  // 打印:0
  }
  render() {
    return (
      <div>
        <div>Demo组件:{this.state.count}</div>
        <button onClick={this.handleClick}>setState更新后执行逻辑</button> 
      </div>
    )
  }
}

总结

setState扩展 - 异步OR同步

在react类组件中,多次的setState并不会立刻执行,而是合并成一个来执行。

知道何时出现“异步”,知道何时出现同步

import React, {Component} from 'react' 
export default class Demo extends Component {
  state = {
    count: 0
  }
  handleClick = () => {
    // 合成事件的处理函数 or 生命周期构造函数
    // this.setState({count: this.state.count+1})
    // this.setState({count: this.state.count+1})
    // 表现异步

    setTimeout(() => {
      this.setState({count: this.state.count+1})
      this.setState({count: this.state.count+1})
    }, 0);
    // 表现同步
  }
  render() {
    console.log('render')
    return (
      <div>
        <div>Demo组件:{this.state.count}</div>
        <button onClick={this.handleClick}>同步OR异步</button> 
      </div>
    )
  }
}
全文完
本文标签: React组件高级React组件进阶react组件校验props校验React生命周期props默认值
本文标题: React组件进阶及生命周期
本文链接: https://www.iyouhun.com/m/?post=225

〓 随机文章推荐

共有1333阅 / 0我要评论
  1. 还没有评论呢,快抢沙发~

发表你的评论吧返回顶部

!评论内容需包含中文

请勾选本项再提交评论