📜  ReactJS setState()

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

ReactJS setState()

所有的 React 组件都可以有一个与之关联的状态。组件的状态可以由于对用户执行的操作的响应或系统触发的事件而改变。每当状态发生变化时,React 都会将组件重新渲染到浏览器。在更新状态值之前,我们需要建立一个初始状态设置。完成后,我们使用setState() 方法更改状态对象。它确保组件已更新并要求重新渲染组件。

语法:我们可以使用 setState() 直接改变组件的状态,也可以通过箭头函数。

setState({ stateName : updatedStateValue })

// OR
setState((prevState) => ({ 
   stateName: prevState.stateName + 1 
}))

创建反应应用程序:

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

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

    cd foldername

示例 1:更新单个属性。

我们在构造函数中设置了初始状态值,并创建了另一个函数updateState()来更新状态。现在,当我们单击按钮时,后者会作为onClick 事件触发,该事件会更改状态值。我们在updateState()函数中执行 setState() 方法,方法是:

this.setState({greeting : 'GeeksForGeeks welcomes you !!'}) 

如您所见,我们将一个对象传递给 setState()。这个对象包含我们想要更新的状态部分,在这种情况下,就是greeting的值。 React 接受这个值并将其合并到需要它的对象中。就像按钮组件询问它应该使用什么来更新 greeting 的值,而 setState() 则以答案作为响应。

App.js
import React, { Component } from 'react'
    
class App extends Component { 
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {greeting : 
          'Click the button to receive greetings'} 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  updateState(){ 
    // Changing state 
    this.setState({greeting : 
                 'GeeksForGeeks welcomes you !!'}) 
  } 
      
  render(){ 
    return ( 
      
         

Greetings Portal

           

{this.state.greeting}

               {/* Set click handler */}                  
      )    }  }       export default App;


App.js
import React, { Component } from 'react'
    
class App extends Component { 
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
      test: "Nil",
      questions: "0",
      students: "0"
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  updateState(){ 
    // Changing state 
    this.setState({
      test: 'Programming Quiz',
      questions: '10',
      students: '30'
    }) 
  } 
      
  render(){ 
    return ( 
      
          

Test Portal

               

{this.state.test}

            

{this.state.questions}

            

{this.state.students}

        {/* Set click handler */}                  
      )    }  }       export default App;


App.js
import React, { Component } from 'react'
    
class App extends Component {
  static defaultProps = { 
    testTopics : [ 
      'React JS', 'Node JS', 'Compound components',  
      'Lifecycle Methods', 'Event Handlers', 
      'Router', 'React Hooks', 'Redux', 
      'Context'
    ] 
  } 
  
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
      testName: "React js Test",
      topics: ''
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  listOfTopics(){ 
    return ( 
      
              {this.props.testTopics.map(topic => (            
  • {topic}
  •           ))}        
      )     }       updateState(){             // Changing state      this.setState({       testName: 'Test topics are:',       topics: this.listOfTopics()     })    }           render(){      return (        
          

Test Information

          

{this.state.testName}

        

{this.state.topics}

        {/* Set click handler */}                  
      )    }  }       export default App;


App.js
import React, { Component } from 'react'
    
class App extends Component {
  
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
       count: 0
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  updateState(){ 
    // Changing state 
    this.setState((prevState) => {
      return { count: prevState.count + 1}
    })  
  }
      
  render(){ 
    return ( 
      
          

Click Counter

                    

You have clicked me {this.state.count} times.

        {/* Set click handler */}                  
      )    }  }     export default App;


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

npm start

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

示例 2:更新多个属性。

组件的状态对象可能包含多个属性,React 允许使用 setState()函数仅更新这些属性的子集,以及使用多个 setState() 方法独立更新每个属性值。

我们通过初始化三个不同的属性来设置我们的初始状态,然后我们创建一个函数updateState() ,它在调用时更新它的值。这个函数再次作为onClick 事件被触发,我们同时获得状态的更新值。

应用程序.js

import React, { Component } from 'react'
    
class App extends Component { 
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
      test: "Nil",
      questions: "0",
      students: "0"
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  updateState(){ 
    // Changing state 
    this.setState({
      test: 'Programming Quiz',
      questions: '10',
      students: '30'
    }) 
  } 
      
  render(){ 
    return ( 
      
          

Test Portal

               

{this.state.test}

            

{this.state.questions}

            

{this.state.students}

        {/* Set click handler */}                  
      )    }  }       export default App;

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

npm start

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

示例 3:使用 props 更新状态值。

我们设置了一个字符串数组testTopics作为我们组件的道具。创建了一个函数listOfTopics来将所有字符串映射为我们状态主题中的列表项。函数updateState被触发并将主题设置为列表项。当我们点击按钮时,我们会得到更新的状态值。这种方法以处理复杂数据和轻松更新状态而闻名。

应用程序.js

import React, { Component } from 'react'
    
class App extends Component {
  static defaultProps = { 
    testTopics : [ 
      'React JS', 'Node JS', 'Compound components',  
      'Lifecycle Methods', 'Event Handlers', 
      'Router', 'React Hooks', 'Redux', 
      'Context'
    ] 
  } 
  
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
      testName: "React js Test",
      topics: ''
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  listOfTopics(){ 
    return ( 
      
              {this.props.testTopics.map(topic => (            
  • {topic}
  •           ))}        
      )     }       updateState(){             // Changing state      this.setState({       testName: 'Test topics are:',       topics: this.listOfTopics()     })    }           render(){      return (        
          

Test Information

          

{this.state.testName}

        

{this.state.topics}

        {/* Set click handler */}                  
      )    }  }       export default App;

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

npm start

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

示例 4.使用之前的值更新状态。

我们创建一个值为 0 的初始状态计数。函数updateState()将状态的当前值在每次调用时递增 1。这次我们通过传递prevState作为参数在箭头函数中使用 setState() 方法。状态的当前值是通过prevState.stateName访问的,每当我们按下按钮时它都会增加 1。当我们以依赖于其先前值的方式在状态中设置值时,此方法非常有用。例如,切换布尔值(真/假)或递增/递减数字。

应用程序.js

import React, { Component } from 'react'
    
class App extends Component {
  
  constructor(props){ 
    super(props) 
        
    // Set initial state 
    this.state = {
       count: 0
    } 
        
    // Binding this keyword 
    this.updateState = this.updateState.bind(this) 
  } 
    
  updateState(){ 
    // Changing state 
    this.setState((prevState) => {
      return { count: prevState.count + 1}
    })  
  }
      
  render(){ 
    return ( 
      
          

Click Counter

                    

You have clicked me {this.state.count} times.

        {/* Set click handler */}                  
      )    }  }     export default App;

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

npm start

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