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.
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: '222' }) } }
You can also write like this
<button onClick={this.show.bind(this)}>按钮</button> show () { console.log(this) this.setState({ msg: '222' }, () => { console.log(this.state.msg) // 更新后的值222 }) console.log(this.state.msg) // 123 }
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.
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!