ReactJS – componentWillUpdate() 方法
在本文中,我们将看到如何在 DOM 树中更新组件之前执行函数。
此方法在 React 生命周期更新阶段使用。此函数通常在组件更新之前或传递给组件的状态或属性发生更改时调用。不要在此函数中调用 setState() 方法。如果 shouldComponentUpdate() 方法返回 false,则此方法将不会被调用。
请注意:此方法现已弃用。
语法
UNSAFE_componentWillUpdate(nextProps, nextState)
示例
在此示例中,我们将构建一个改变颜色的 React 应用程序,当组件在 DOM 树中更新时,它会调用 componentWillUpdate 方法。
以下示例中的第一个组件是 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_componentWillUpdate(nextProps, nextState) {
console.log('Component will be updated soon');
}
render() {
console.log('ChangeName component is called');
return (
<div>
<h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
</div>
);
}
}
export default App;输出
这将产生以下结果。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP