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的值
注意事項
避免濫用:
getDerivedStateFromProps應該謹慎使用,因為它可能會導致代碼難以理解和維護。通常情況下,直接使用 props 而不是從 props 中派生 state 是更好的做法。性能問題:頻繁地在
getDerivedStateFromProps中更新 state 可能會導致性能問題,因為這可能會觸發不必要的重新渲染。替代方案:如果你發現自己經常需要使用
getDerivedStateFromProps,可以考慮重新審視你的組件結構,或者使用其他生命周期方法來實現相同的功能。例如,componentDidUpdate提供了一個更好的地方來處理 props 的變化,而不會觸發不必要的重新渲染。

浙公網安備 33010602011771號