props - 类型校验
- 理解props都是外来的,在使用的时候如果数据类型不对,很容易造成组件内部逻辑出错
1 2 3 4 5 6 7 8 9 10 11
| const List = props => { const arr = props.colors const list = arr.map((item, index) => <li key={index}>{item.name}</li>) return ( <ul>{list}</ul> ) }
<List colors={19} />
|
报错:TypeError: arr.map is not a function
1 2 3 4 5 6 7 8 9 10 11 12
| 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 = { colors: PropTypes.array }
|
Props - 类型校验常见类型
常见的校验规则
- 常见类型:array、bool、func、number、object、string
- React元素类型:element
- 必填项:isRequired
- 特定结构的对象:shape({})
校验规则的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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的默认值
1 2 3 4 5 6 7 8 9 10
| const Pagination = (props) => { return <div> pageSize的默认值:{props.pageSize}</div> }
Pagination.defaultProps = { pageSize: 10 }
<Pagination />
|
新版react推荐使用参数默认值来实现
1 2 3 4 5 6
| const Pagination = ({pageSize = 10}) => { return <div> pageSize的默认值:{pageSize}</div> }
<Pagination />
|
props - 静态属性写法
类的静态属性
- 实例属性需要实例化后,通过实例访问
- 静态属性,可以通过类直接访问
1 2 3 4 5 6 7 8 9 10 11
| class Person { gender = '男' static age = 18 }
console.log(Person.age)
const p = new Person() console.log(p.gender)
|
类组件中 propTypes defaultProps 的使用
- 在类组件中通过
static propTypes = {}
定义props校验规则 static defaultProps = {}
定义props默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Demo extends Component { static propTypes = { colors: PropTypes.array, gender: PropTypes.oneOf(['男', '女']).isRequired } static defaultProps = { gender: '男' } render() { return <div>Demo组件</div> } }
|
生命周期 - 概览
什么是组件生命周期

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

生命周期的意义
- 助于理解组件的运行方式、完成更复杂的组件功能、分析组件错误原因
- 钩子函数为开发人员在不同阶段操作组件提供了时机
总结:只有类组件才有生命周期,分为 挂载阶段
更新阶段
卸载阶段
生命周期 - 挂载阶段
执行顺序
constructor() –> render() –> componentDidMount()
触发时机及作用
钩子函数 | 触发时机 | 作用 |
---|
constructor | 创建组件时,最先执行 | 1. 初始化state 2. 创建 Ref 3. 使用 bind 解决 this 指向问题等 |
render | 每次组件渲染都会触发 | 渲染UI(注意: 不能调用setState() ) |
componentDidMount | 组件挂载(完成DOM渲染)后 | 1. 发送网络请求 2.DOM操作 |
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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()
何时触发更新阶段
- setState()
- forceUpdate() 强制组件更新
- 组件接收到新的props(实际上,只需要父组件更新,子组件就会重新渲染)
触发时机及作用
钩子函数 | 触发时机 | 作用 |
---|
render | 每次组件渲染都会触发 | 渲染UI(与 挂载阶段 是同一个render) |
componentDidUpdate | 组件更新(完成DOM渲染)后 | DOM操作,可以获取到更新后的DOM内容,不要直接调用setState |
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| 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 | 组件卸载(从页面中消失) | 执行清理工作(比如:清理定时器等) |
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| 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会合并。
- 理解setState是“异步”的,理解setState会合并更新
- 调用 setState 时,将要更新的状态对象,放到一个更新队列中暂存起来(没有立即更新)
- 如果多次调用 setState 更新状态,状态会进行合并,后面覆盖前面
- 等到所有的操作都执行完毕,React 会拿到最终的状态,然后触发组件更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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) } render() { console.log('render') return ( <div> <div>Demo组件:{this.state.count}</div> <button onClick={this.handleClick}>体现“异步”和合并</button> </div> ) } }
|
- React这么处理的好处是什么?
- “异步” 更新,或者做延时更新,为了等所有操作结束后去更新
- 合并更新,是将多次setState合并,然后进行更新
- 都是为了提高渲染性能
setState扩展 - 更多用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import React, {Component} from 'react' export default class Demo extends Component { state = { count: 0 } handleClick = () => { this.setState(prevState=>{ return { count: prevState.count + 1 } }) this.setState(prevState=>{ return { count: prevState.count + 1 } }) this.setState(prevState=>{ return { count: prevState.count + 1 } }) } render() { return ( <div> <div>Demo组件:{this.state.count}</div> <button onClick={this.handleClick}>setState串联更新数据</button> </div> ) } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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) }) console.log('未更新:', this.state.count) } render() { return ( <div> <div>Demo组件:{this.state.count}</div> <button onClick={this.handleClick}>setState更新后执行逻辑</button> </div> ) } }
|
总结
- 使用
setState((prevState) => {})
语法,可以解决多次调用状态依赖问题 - 使用
setState(updater[, callback])
语法,在状态更新(页面完成重新渲染)后立即执行某个操作
setState扩展 - 异步OR同步
在react类组件中,多次的setState并不会立刻执行,而是合并成一个来执行。
- setState本身并不是一个异步方法,其之所以会表现出一种“异步”的形式,是因为react框架本身的一个性能优化机制
- React会将多个setState的调用合并为一个来执行,也就是说,当执行setState的时候,state中的数据并不会马上更新
知道何时出现“异步”,知道何时出现同步
- setState如果是在react的生命周期中或者是事件处理函数中,表现出来为:延迟合并更新(“异步更新”)
- setState如果是在setTimeout/setInterval或者原生事件中,表现出来是:立即更新(“同步更新”)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import React, {Component} from 'react' export default class Demo extends Component { state = { count: 0 } handleClick = () => { 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> ) } }
|