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