React getSnapshotBeforeUpdate() method

React 组件生命周期React Component Lifecycle

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

getSnapshotBeforeUpdate(prevProps, prevState)

The getSnapshotBeforeUpdate() method is called before the most recent rendered output (committed to the DOM node).

In the getSnapshotBeforeUpdate() method, we can access the props and state before the update.

The getSnapshotBeforeUpdate() method needs to be used together with the componentDidUpdate() method, otherwise an error will occur.

The following example uses thegetSnapshotBeforeUpdate()method to view the value of the state object before the update. The example will display the different values before and after the update after a 1-second delay:

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "example"}; } componentDidMount() { setTimeout(() => { this.setState({favoritesite: "google"}) }, 1000) } getSnapshotBeforeUpdate(prevProps, prevState) { document.getElementById("div1").innerHTML = "The favorite website before update is:" + prevState.favoritesite; } componentDidUpdate() { document.getElementById("div2").innerHTML = "The favorite website after update is:" + this.state.favoritesite; } render() { return ( <div> <h1> My favorite website is{this.state.favoritesite}</h1> <div id="div1"></div> <div id="div2"></div> </div> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Header />);

Try it »

React 组件生命周期React Component Lifecycle

Other Extensions