React getSnapshotBeforeUpdate () method


Release date:2024-03-14 Update date:2024-03-15 Editor:admin View counts:176

Label:

React getSnapshotBeforeUpdate () method

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

getSnapshotBeforeUpdate(prevProps, prevState)

getSnapshotBeforeUpdate() method is called before the last rendered output (submitted to the DOM node).

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

getSnapshotBeforeUpdate() the method needs to be the same as the componentDidUpdate() method, otherwise an error will occur.

The following examples use the getSnapshotBeforeUpdate() method to viewthe update before state object, the instance will display different values before and after the update after a 1-second delay:

Example

classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}componentDidMount(){setTimeout(()=>{this.setState({favoritesite:"google"})},1000)}getSnapshotBeforeUpdate(prevProps,prevState){document.getElementById("div1").innerHTML="What was your favorite website before the update:"+prevState.favoritesite;}componentDidUpdate(){document.getElementById("div2").innerHTML="What is your favorite website after the update:"+this.state.favoritesite;}render(){return(<div>
<h1>My favorite website is{this.state.favoritesite}</h1> <divid="div1"></div>
<divid="div2"></div>
</div>);}}ReactDOM.render(<Header/>,document.getElementById('root'));

Powered by TorCMS (https://github.com/bukun/TorCMS).