getSnapshotBeforeUpdate()方法在呈現DOM之前被調用。用於在DOM更新後存儲狀態的先前值。
getSnapshotBeforeUpdate()方法返回的任何值都將用作componentDidUpdate()方法的參數。此函數始終與componentDidUpdate()方法一起使用,反之亦然。
用法:
getSnapshotBeforeUpdate(prevProps, prevState)
參數:它接受兩個參數,它們是prevProps和prevState隻是相關組件為re-rendered之前的道具或狀態。
創建React應用程序:
步驟1:使用以下命令創建React應用程序:
npx create-react-app foldername
步驟2:建立專案資料夾(即資料夾名稱)之後,使用以下指令移至該資料夾:
cd foldername
例:程序演示了使用getSnapshotBeforeUpdate()方法。在這裏,我們將使用狀態的先前值和當前值來顯示一些文本。
文件名:App.js:
Javascript
import React from 'react';
class App extends React.Component {
// Initializing the state
state = {
name:'GFG',
};
componentDidMount() {
// Changing the state after 1 sec
setTimeout(() => {
this.setState({ name:'GeeksForGeeks' });
}, 1000);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Displaying the previous value of the state
document.getElementById('prev').innerHTML =
'Previous Name:' + prevState.name;
}
componentDidUpdate() {
// Displaying the current value of the state
document.getElementById('new').innerHTML =
'Current Name:' + this.state.name;
}
render() {
return (
<div>
<div id="prev"></div>
<div id="new"></div>
</div>
);
}
}
export default App;
運行應用程序的步驟:從項目的根目錄中使用以下命令運行應用程序:
npm start
輸出:
參考:https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate
相關用法
- ReactJS shouldComponentUpdate()用法及代碼示例
- ReactJS componentDidMount()用法及代碼示例
- ReactJS bind()用法及代碼示例
- ReactJS componentDidUpdate()用法及代碼示例
- ReactJS componentDidCatch()用法及代碼示例
- ReactJS getDerivedStateFromError()用法及代碼示例
- ReactJS componentWillUnmount()用法及代碼示例
注:本文由純淨天空篩選整理自rbbansal大神的英文原創作品 ReactJS getSnapshotBeforeUpdate() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。