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

相关推荐
友莘居士2 天前
Dify中的Agent和发现和调用mcp工具两个节点调用的异同
agent·react·dify·functioncalling·mcp
aiguangyuan3 天前
前端开发性能优化概要
系统架构·vue·react·前端开发
叶 落7 天前
Component cannot be used as a JSX component
typescript·react
小浣熊喜欢揍臭臭9 天前
react+antd+表格拖拽排序以及上移、下移、移到顶部、移到底部
前端·前端框架·react
小浣熊喜欢揍臭臭9 天前
react+antd 可拖拽模态框组件
前端·javascript·react
人肉推土机11 天前
Planning Agent:基于大模型的动态规划与ReAct机制,实现复杂问题自适应执行求解
大模型·动态规划·react·planning agent
伍哥的传说11 天前
Webpack5 新特性与详细配置指南
webpack·前端框架·vue·vue3·react·webpack5·前端构建
止观止14 天前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
前端风云志14 天前
Ant Design如何自定义输入框(Input)组件样式
react·ant design
爱看书的小沐16 天前
【小沐杂货铺】基于Three.JS绘制汽车展示Car(WebGL、vue、react、autoshow、提供全部源代码)
汽车·vue3·react·webgl·three.js·opengl·autoshow