📜  ReactJS UNSAFE_componentWillReceiveProps() 方法

📅  最后修改于: 2022-05-13 01:56:44.505000             🧑  作者: Mango

ReactJS UNSAFE_componentWillReceiveProps() 方法

在我们挂载的 React 组件接收到新的 props 之前调用componentWillReceiveProps() 。它在React Life-cycle的更新阶段被调用。它用于更新状态以响应我们道具的一些变化。我们不能在挂载期间使用初始 props 调用它,因为 React 仅在我们的组件的 props 更新时才调用此方法。

根据这个问题,在最新版本的 React 中已弃用 componentWillReceiveProps() 方法。建议使用getDerivedStateFromProps() 方法代替它,但如果我们仍然想使用 componentWillReceiveProps() ,我们可以通过将其称为UNSAFE_componentWillReceiveProps()来实现。根据 React 不建议使用此方法,这就是为什么UNSAFE关键字在开头出现的原因是为了给所有 React 开发者一个温和的信息,停止使用此方法。当组件的状态取决于 props 的变化时,可以使用此方法。

句法:

class App extends Component {
  UNSAFE_componentWillReceiveProps(newProps) {
    // Action you want to execute
  }
}

参数:它接受一个参数,它是newProps ,它是组件在DOM中渲染后的更新值。

创建反应应用程序:

  • 第 1 步:使用以下命令创建一个React 应用程序

    npx create-react-app foldername

  • 第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:
    cd foldername

项目结构:它将如下所示。

示例:在此示例中,我们将构建一个在控制台上记录更新后的 prop 值的应用程序。现在在 App.js 文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

App.js
import React from 'react'
  
class App extends React.Component {
  
  constructor(props) {
     super(props)
  
     // Set initial state
     this.state = {
        count: 0
     }
  
     // Binding this keyword
     this.handleCount = this.handleCount.bind(this)
  };
  
  handleCount() {
    // Updating state
     this.setState({
       count: this.state.count + 1
     })
  }
  
  render() {
     return (
        // Passing state as props
        
                                
     );   } }    class PropComponent extends React.Component {      UNSAFE_componentWillReceiveProps(newProps) {         // Performing an action        console.log('Component is receiving new props', newProps);   }      render() {      return (            // Printing updated props value         
          

My value is {this.props.data}

        
     );   } }    export default App;


运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出:

说明:我们在App类组件中创建一个初始值为 0 的计数状态和一个用于将其当前值增加 1 的函数handleCount 。当我们单击按钮元素时,后者会作为onClick 事件触发。当我们单击按钮时,我们的状态值会增加,并且这个更新的值作为道具传递给另一个类组件PropComponent 。在我们的 PropComponent 接收新的 props 之前,它会通过UNSAFE_componentWillReceiveProps(newProps) 方法在控制台上记录更新的 props 值。这样,我们可以在组件接收到新的 props 之前执行任何操作。

当我们的组件加载时,控制台顶部还会出现一条警告消息,它清楚地告诉我们,不建议将这种方法用于我们上面已经讨论过的用途。