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 的变化,而不会触发不必要的重新渲染。

相关推荐
HaanLen2 天前
React19源码系列之createRoot的执行流程是怎么的?
react·react19源码
只会写Bug的程序员4 天前
面试之《前端常见的设计模式》
前端·设计模式·面试·react
末日的狂欢姐4 天前
AXUI前端框架v3版本已经发布,底层完全改写,基于原生技术标准,想走得更远!
javascript·typescript·前端框架·vue·react·axui
yangkei6 天前
React 学习笔记
笔记·学习·react.js·react
智绘前端9 天前
React Native国际化实践(react-i18next)
前端·javascript·react native·react.js·react
背太阳的牧羊人10 天前
create_react_agent(model, tools) 和 graph_builder.add_conditional_edges 的联系和区别
人工智能·agent·react·tools·langgraph·聊天模型
孤蓬&听雨11 天前
前端开发10大框架深度解析
前端·vue·框架·react·开发·nuxt·next
i建模13 天前
Tauri+React跨平台开发全场景问题解析
前端框架·react·tauri·跨平台开发
i建模13 天前
Tauri+React跨平台开发环境搭建全指南
前端框架·react·tauri·跨平台开发
i建模13 天前
Tauri+React+Ant Design跨平台开发环境搭建指南
前端框架·react·tauri·ant design·跨平台开发