📜  ReactJS UNSAFE_componentWillUpdate() 方法

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

ReactJS UNSAFE_componentWillUpdate() 方法

componentWillUpdate() 方法为我们提供了在 React 组件接收到新的 props 或状态值之前对其进行操作的控件。在React 生命周期的更新阶段,在渲染我们的组件之前调用它,即在更新 State 或 Props 之后和执行 render()函数之前触发此方法。

根据这个问题,在最新版本的 React 中已弃用 componentWillUpdate() 方法。建议使用getSnapshotBeforeUpdate() 方法作为替代方法,但如果我们仍想使用 componentWillUpdate(),我们可以通过将其称为UNSAFE_componentWillUpdate()来实现。根据 React 不建议使用此方法,这就是为什么UNSAFE关键字在开头出现的原因是为了给所有 React 开发者一个温和的信息,停止使用此方法。此方法可用于根据更新的 state/prop 值执行操作。

句法:

class App extends Component {
  UNSAFE_componentWillUpdate(Props, State) {  
    // Action you want to execute
  }
}

参数:它接受两个参数,它们是PropsState ,它们是组件重新渲染之前 props 或 state 的更新值。

创建反应应用程序:

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

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

    cd foldername

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

示例:在此示例中,我们将构建一个应用程序,当状态值更新时,它会在控制台上打印一条消息。

App.js:现在在 App.js 文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

Javascript
import React from 'react'; 
class App extends React.Component { 
    
  // Initializing the state 
  state = { 
    content: '', 
  }; 
  
  componentDidMount() { 
  
      // Updating the state
      this.setState({
         content: 'GeeksForGeeks'
      })
   } 
    
  UNSAFE_componentWillUpdate(Props, State) { 
  
    // Performing an action
    alert(`Your state value has changed to ${State.content}`);
  } 
  
  render() { 
    return ( 
  
      // Printing the state value
      
          

State value is {this.state.content}

      
      );    }  }       export default App;


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

npm start

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

说明:我们收到一条警报消息,表明我们的状态内容 已通过 UNSAFE_componentWillUpdate() 方法更新 然后我们的组件重新渲染并向我们显示更新的状态值(我们正在通过 render() 方法打印该值)。这样,我们可以在重新渲染组件之前执行任何需要更新状态/道具值的操作。如您所见,控制台上还会出现一条警告消息,清楚地表明不建议使用我们上面已经讨论过的这种方法。