📜  ReactJS 中的 forceUpdate 与 render 有什么区别?

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

ReactJS 中的 forceUpdate 与 render 有什么区别?

render():在 React 中,当您使用类组件时,render() 方法是最重要的。没有这个方法,类组件就不能返回值。所有的 HTML 代码都写在 render() 方法中。 render() 是 React 组件生命周期方法的一部分。它在不同的应用程序阶段被调用。例如,当组件首次制造或准备就绪时。

例子:

App.js
import React,{ Component } from 'react';
  
class App extends Component {
 render() {
   return (    
     
        

           Learn React from GFG!!         

     
    )   } }        export default App;


App.js
import React from 'react';
class App extends React.Component{
  forceUpdateHandler=()=>{
    this.forceUpdate();
  };
    
  render(){
   console.log('Component is re-rendered');
    return(
      
       

        Example of forceUpdate()          method to show re-rendering        

                 

Random Number :              { Math.floor(Math.random() * (100 - 1 +1)) + 1 }         

      
    );   } }    export default App;


输出:

forceUpdate():在 React 中,当组件的 props 和 state 发生变化时,组件会自动重新渲染,但是当组件依赖于 state 和 props 以外的某些数据时。在这种情况下,调用 forceUpdate 以告知该组件需要重新渲染。调用 forceUpdate() 将强制重新渲染组件,从而跳过 shouldComponentUpdate() 方法调用组件上的 render() 方法。

例子:

应用程序.js

import React from 'react';
class App extends React.Component{
  forceUpdateHandler=()=>{
    this.forceUpdate();
  };
    
  render(){
   console.log('Component is re-rendered');
    return(
      
       

        Example of forceUpdate()          method to show re-rendering        

                 

Random Number :              { Math.floor(Math.random() * (100 - 1 +1)) + 1 }         

      
    );   } }    export default App;

输出:

强制性升级

forceUpdate 与渲染之间的区别:

render()

forceUpdate()

This method is called in the following conditions:

  • When a component is instantiated.
  • When state or props is updated.
It will be called when some data changes other than state or props.
It does not skip any lifecycle method.It skips the lifecycle shouldComponentUpdate method.
It is not user-callable.It is called manually.
It automatically re-renders whenever required.It re-render the component forcefully.
It is compulsory to use as it is the only required method in the Class component.It is not recommended to use. It should be avoided.