React getDerivedStateFromProps() Method

React 组件生命周期React Component Lifecycle

The format of the getDerivedStateFromProps() method is as follows:

static getDerivedStateFromProps(props, state)

getDerivedStateFromProps is called before the render method, i.e., before DOM elements are rendered, and it is called during both initial mounting and subsequent updates.

The value of state depends on props at all times.

getDerivedStateFromProps exists for one purpose only: to let the component update state when props change.

This method returns an object to update state, or null to update nothing.

The following examplefavoritesitehas an initial value ofexample, butgetDerivedStateFromProps()the method usesfavsiteproperty to updatefavoritesitethe value of:

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "example"}; } static getDerivedStateFromProps(props, state) { return {favoritesite: props.favsite }; } render() { return ( <h1>My favorite website is{this.state.favoritesite}</h1> ); } }

Try it »

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "example"}; } shouldComponentUpdate() { return true; //Modify here to allow the component to update } changeSite = () => { this.setState({favoritesite: "google"}); } render() { return ( <div> <h1>My favorite website is{this.state.favoritesite}</h1> <button type="button" onClick={this.changeSite}>Modify</button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Header />);

Try it »

React 组件生命周期React Component Lifecycle

Other Extensions