Home > Web Front-end > JS Tutorial > body text

How to change the value of state in react

藏色散人
Release: 2020-12-17 11:06:36
Original
3975 people have browsed it

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;
    })
  }
}
Copy after login

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
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template