ReactJS – componentWillReceiveProps() 方法
在本文中,我們將瞭解如何執行一個函式,如果傳遞給元件的 props 在 DOM 樹中更新。
此方法在 React 生命週期更新階段使用。 如果傳遞給元件的 props 更改,通常會呼叫此函式。它用於根據接收到的新 props 更新狀態。**setState()** 方法通常不會再次呼叫此方法。
注意:此方法現已棄用。
語法
UNSAFE_componentWillReceiveProps(nextProps)
示例
在此示例中,我們將構建一個變色 React 應用程式,當元件的 props 在更新時,這個應用程式將呼叫 **componentWillReceiveProps **方法。
在以下示例中,我們的第一個元件是 App。此元件是 **ChangeName** 元件的父元件。 我們單獨建立 **ChangeName**,然後在我們的 App 元件中將其新增到 JSX 樹中。因此,只需要匯出 App 元件。
App.jsx
import React from 'react';
class App extends React.Component {
state = { color: 'green' };
render() {
setTimeout(() => {
this.setState({ color: 'wheat' });
}, 4000);
return (
<div>
<h1>Tutorialspoint</h1>
<ChangeName color={this.state.color} />
</div>
);
}
}
class ChangeName extends React.Component {
UNSAFE_componentWillReceiveProps(nextProps) {
console.log('Component received new props', nextProps);
}
render() {
console.log('ChangeName component is called');
return (
<div>
<h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
</div>
);
}
}
export default App;輸出
這將產生以下結果。

廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP