Home  >  Article  >  Web Front-end  >  How to modify component status in react

How to modify component status in react

WBOY
WBOYOriginal
2022-04-29 13:35:252601browse

In react, you can use setState() to modify the state of the component. setState() is a method used to update the component state. This method can queue changes to the component state and also obtain the latest The state, the syntax is "setState(updater,[callback function])".

How to modify component status in react

The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.

How to modify the component state in react

In React, the state of the component cannot be modified directly. It needs to be modified through setState()

In react, setstate is used Method to update component state; setState() queues changes to component state and notifies React that it needs to re-render this component and its subcomponents using the updated state. The syntax is "setState(object, [callback function]) ".

Syntax:

setState(updater[, callback])

updater updater

callback callback function executed after update

Modify status

For example, if you want to change the content value in state to 'Xiangxiang'

state = {
  content: '大熊'
}

You cannot trigger the update of the view by directly modifying it:

this.state.content = '香香'

You need to modify it through setState:

this.setState({
  content: '香香'
})

Get the latest status value

Because setState() is asynchronous, you may not be able to get the latest value after modifying the status. If you want to get the latest The state value can provide a callback function for setState(). This callback will be executed after the state is updated. The latest state can be obtained in the callback function

Example:

this.setState({
  content: '香香'
}, () => {
  // 通回调获取最新的状态
  console.log(this.state.content)
})

setState() The first parameter can also be a function. This function receives two parameters: the first parameter is the state value before update, and the second parameter is props (which can obtain the data passed by the parent component); when modifying the state, it involves This form can be used when reaching the previous state value.

this.setState((state, props) => {
  console.log(state.content, props)
  // 返回一个对象
  return {
    content: prev.content + '香香'
  }
})

Recommended learning: "react video tutorial"

The above is the detailed content of How to modify component status 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