Home  >  Article  >  Web Front-end  >  How to change the value of state in react

How to change the value of state in react

藏色散人
藏色散人Original
2020-12-17 11:06:363987browse

How to change the state value in react: First open the corresponding react code file; then use the "this.setState({key name: value})" method provided by React to modify the state value.

How to change the value of state in react

The operating environment of this tutorial: windows7 system, react17.0.1 version, this method is suitable for all brands of computers.

Related recommendations: "react tutorial"

Changing the value of state in react

import React from 'react'
 
export default  class ClickS extends React.Component {
  constructor () {
    super()
    this.state= {
      msg: '123'
    }
  }
  render () {
    return <div>
      <button onClick={()=>this.show()}>按钮</button>
      <h2>{this.state.msg}</h2>
    </div>
  }
  show () {
    console.log(this)
    this.setState({
      msg: &#39;222&#39;
    })
  }
}

How to change the value of state in react

You can also write like this

<button onClick={this.show.bind(this)}>按钮</button>
show () {
  console.log(this)
  this.setState({
    msg: &#39;222&#39;
  }, () => {
    console.log(this.state.msg) // 更新后的值222
  })
  console.log(this.state.msg) // 123
}

How to change the value of state in react

Note:

If you want to reassign the data in the state in React, do not use this.state.xxx = value. You should use this.setState({key name: value}) provided by React to make modifications.

If this.state has multiple values ​​and only one of them is modified, it will not affect the other values. SetState will only update the corresponding state value and will not overwrite other state values.

How to change the value of state in react

At the same time, the execution of this.setState method is asynchronous. So I want to get the latest status value. Need to pass callback function.

The above is the detailed content of How to change the value of state in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn