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

相关推荐
Liigo2 天前
初次体验Tauri和Sycamore (2)
rust·react·tauri·webassembly·jsx·sycamore·dioxus
Lysun00122 天前
redux 结合 @reduxjs/toolkit 的使用
开发语言·前端·javascript·react·redux
远洋录23 天前
支付宝八折事件启示录:用户体验与风险管理的平衡艺术
前端·人工智能·react
迪迦23 天前
React实现拖拽特效
javascript·react
远洋录24 天前
Electron 开发者的 Tauri 2.0 实战指南:文件系统操作
前端·人工智能·react
远洋录24 天前
Electron 开发者的 Tauri 2.0 实战指南:安全实践
前端·人工智能·react
远洋录1 个月前
Vue 开发者的 React 实战指南:测试篇
前端·人工智能·react
远洋录1 个月前
Vue 开发者的 React 实战指南:表单处理篇
前端·人工智能·react
ASER_19891 个月前
再谈Redux
javascript·typescript·react·redux·redux-toolkit·hooks·toolkit·html5移动前端·redux-hooks