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

相关推荐
在未来等你5 小时前
AI Agent设计模式 Day 19:Feedback-Loop模式:反馈循环与自我优化
设计模式·llm·react·ai agent·plan-and-execute
A3608_(韦煜粮)14 小时前
深入理解React Hooks设计哲学与实现原理:从闭包陷阱到并发模式
javascript·性能优化·react·前端开发·react hooks·并发模式·自定义hooks
safestar20123 天前
React 性能优化之Fiber 架构深度解析:从堆栈调和到增量渲染的革命
前端·javascript·react
aiguangyuan5 天前
React 18 源码解读(一)
javascript·react·前端开发
aiguangyuan5 天前
React 中什么是可中断更新?
javascript·react·前端开发
人工智能训练6 天前
前端框架选型破局指南:Vue、React、Next.js 从差异到落地全解析
运维·javascript·人工智能·前端框架·vue·react·next.js
aiguangyuan7 天前
React中Context 的作用及原理
javascript·react·前端开发
一只小阿乐7 天前
react 中的判断显示
前端·javascript·vue.js·react.js·react
fredricen9 天前
用LangChain1.0搭建第一个天气查询智能体
llm·agent·react·langchaian
在未来等你9 天前
AI Agent设计模式 Day 7:Tree-of-Thoughts模式:树形思维探索
设计模式·llm·react·ai agent·plan-and-execute