getDerivedStateFromProps 详解

getDerivedStateFromProps 是 React 生命周期中的一个静态方法,主要用于在组件接收到新的 props 时更新 state。这个方法在组件的初始渲染和后续的每次更新(即每次接收到新的 props 或 state)时都会被调用。

详解

  • 静态方法 :这意味着你不能在这个方法中使用 this 关键字。它的第一个参数是新的 props,第二个参数是当前的 state。

  • 返回值getDerivedStateFromProps 必须返回一个对象来更新 state,或者返回 null 表示不需要更新 state。

  • 作用:这个方法的主要作用是确保组件的 state 总是与 props 保持一致。这是一个非常罕见的需求,因为通常我们希望 props 只是初始数据来源,而不是 state 的来源。然而,在某些特殊的场景中,可能需要根据 props 的变化来更新 state。

复制代码
import React, { useId } from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
//import PagerContainer from './components/PagerContainer';
import CheckBoxGroup from './components/common/CheckBoxGroup';

const root = ReactDOM.createRoot(document.getElementById('root'));
class Test1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        }
    }
    render(){
        return (
            <div>
                <h1 onClick={()=>this.setState((state)=>({count:state.count+1}))}>父:{this.state.count}</h1>          
                <Test2 num={this.state.count} />
            </div>
        )
    }
}
class Test2 extends React.Component {
    //设置初始state的数据来源于父组件的props属性
    state = {
        count: this.props.num
    }
    constructor(props) {
        super(props);
    }
    static getDerivedStateFromProps(props, state) {
        console.log('初始渲染和活跃更新阶段都会执行')
        console.log(props, state);
        return {
            count: props.num
        }
    }
    componentDidMount(){

    }
    render() {
      return (
        <div>
            <h1 onClick={()=>this.setState((state)=>({count:state.count+1}))}>这是子组件:{this.state.count}</h1>
        </div>
      )
    }
}
root.render(<Test1 />);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

这个实例的作用是每当Test2组件接收到新的props.num时,都会将state.count的值更新为props.num的值

注意事项

  1. 避免滥用getDerivedStateFromProps 应该谨慎使用,因为它可能会导致代码难以理解和维护。通常情况下,直接使用 props 而不是从 props 中派生 state 是更好的做法。

  2. 性能问题 :频繁地在 getDerivedStateFromProps 中更新 state 可能会导致性能问题,因为这可能会触发不必要的重新渲染。

  3. 替代方案 :如果你发现自己经常需要使用 getDerivedStateFromProps,可以考虑重新审视你的组件结构,或者使用其他生命周期方法来实现相同的功能。例如,componentDidUpdate 提供了一个更好的地方来处理 props 的变化,而不会触发不必要的重新渲染。

相关推荐
阿࿆杰࿆10 小时前
solon-flow基于bpmnJs的流程设计器
vue·流程图·react
许泽宇的技术分享1 天前
ReAct Agent:让AI像人类一样思考与行动的革命性框架
人工智能·agent·react
青衫客363 天前
用 Python 实现一个“小型 ReAct 智能体”:思维链 + 工具调用 + 环境交互
python·大模型·llm·react
柯北(jvxiao)10 天前
Vue vs React 多维度剖析: 哪一个更适合大型项目?
前端·vue·react
袋鼠云数栈前端10 天前
扣子 Coze 产品体验功能
大数据·ai·react
想你依然心痛15 天前
React 表单处理:移动端输入场景下的卡顿问题与防抖优化方案
react
亦世凡华、20 天前
React--》实现 PDF 文件的预览操作
经验分享·pdf·react·pdf预览
技术路上的探险家21 天前
Web3:在 VSCode 中使用 Vue 前端与已部署的 Solidity 智能合约进行交互
vscode·web3·区块链·交互·react·solidity·ethers.js
友莘居士1 个月前
Dify中的Agent和发现和调用mcp工具两个节点调用的异同
agent·react·dify·functioncalling·mcp
aiguangyuan1 个月前
前端开发性能优化概要
系统架构·vue·react·前端开发