依安县建设网站,龙岗做网站,网站上传后后台进不去,网站空间登录React 中的生命周期函数可以分为三个阶段#xff1a;Mounting#xff08;挂载#xff09;#xff0c;Updating#xff08;更新#xff09;和 Unmounting#xff08;卸载#xff09;。每个阶段都有不同的函数#xff0c;用于执行不同的操作。
Mounting#xff08;挂载…React 中的生命周期函数可以分为三个阶段Mounting挂载Updating更新和 Unmounting卸载。每个阶段都有不同的函数用于执行不同的操作。
Mounting挂载
Mounting 阶段是组件实例化并插入到 DOM 中的阶段。在这个阶段中有以下几个函数
constructor()构造函数用于初始化组件的 state 和绑定事件处理函数。
constructor(props) {super(props);this.state { count: 0 };this.handleClick this.handleClick.bind(this);
}static getDerivedStateFromProps()当组件接收到新的 props 时会调用此函数返回一个对象来更新 state或者返回 null 表示不更新 state。
static getDerivedStateFromProps(nextProps, prevState) {if (nextProps.value ! prevState.value) {return { value: nextProps.value };}return null;
}render()渲染组件到 DOM 中。
render() {return (divpCount: {this.state.count}/pbutton onClick{this.handleClick}Click me/button/div);
}componentDidMount()组件挂载到 DOM 后调用通常用于发送网络请求、设置定时器等操作。
componentDidMount() {fetch(https://api.example.com/data).then(response response.json()).then(data this.setState({ data }));
}Updating更新
Updating 阶段是组件状态或属性更新时的阶段。在这个阶段中有以下几个函数
shouldComponentUpdate()当组件接收到新的 props 或 state 时会调用此函数返回 true 表示需要更新组件返回 false 表示不需要更新组件。
shouldComponentUpdate(nextProps, nextState) {if (nextProps.value ! this.props.value || nextState.count ! this.state.count) {return true;}return false;
}static getDerivedStateFromProps()同 Mounting 阶段的 getDerivedStateFromProps() 函数。render()同 Mounting 阶段的 render() 函数。componentDidUpdate()组件更新后调用通常用于操作 DOM 或发送网络请求。
componentDidUpdate(prevProps, prevState) {if (prevProps.value ! this.props.value) {fetch(https://api.example.com/data?value${this.props.value}).then(response response.json()).then(data this.setState({ data }));}
}Unmounting卸载
Unmounting 阶段是组件从 DOM 中移除的阶段。在这个阶段中有以下几个函数
componentWillUnmount()组件卸载前调用通常用于清理定时器或取消网络请求等操作。
componentWillUnmount() {clearTimeout(this.timer);
}需要注意的是在 React 16.8 之后引入了 Hooks 的概念可以使用 useEffect 等 Hook 来代替生命周期函数。例如
import React, { useState, useEffect } from react;function Example() {const [count, setCount] useState(0);useEffect(() {document.title You clicked ${count} times;});return (divpYou clicked {count} times/pbutton onClick{() setCount(count 1)}Click me/button/div);
}在这个例子中useEffect 函数在组件挂载后和每次更新后都会调用用于更新文档标题。