ReactJS - componentWillMount() 方法
在本文中,我們將瞭解如何在元件載入到 DOM 樹中之前執行函式。
此方法是在 React 生命週期中的裝載階段期間使用的。此函式通常在元件載入到 DOM 樹中之前呼叫。此方法在呼叫 render() 方法之前呼叫,因此可用於初始化狀態,但還是首選建構函式。
此方法通常用於伺服器端渲染。不要在此方法中呼叫訂閱或副作用;可改為使用 componentDidMount。
注意:此方法現已棄用。
語法
UNSAFE_componentWillMount()
示例
在此示例中,我們將構建一個變色 React 應用程式,此應用程式在元件載入到 DOM 樹後立即更改文字顏色。
以下示例中的第一個元件是 App。此元件是 ChangeName 元件的父級。我們單獨建立 ChangeName,然後只將其新增到 App 元件中的 JSX 樹中。因此,只需要匯出 App 元件即可。
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>Tutorialspoint</h1>
<ChangeName />
</div>
);
}
}
class ChangeName extends React.Component {
constructor(props) {
super(props);
this.state = { color: 'lightgreen' };
}
UNSAFE_componentWillMount() {
// Changing the state immediately.
this.setState({ color: 'wheat' });
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>
</div>
);
}
}
export default App;輸出
這將生成以下結果。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP