Learn the useState Hook of React Hook together

Get into the habit of writing together! This is the first day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

What is useState Hook?

It allows us to have responsive variable state and modify the state when writing functional components with React.

Use useState Hook

The core is the useState function, which is used to create a responsive variable and a function that can modify the responsive variable.

Let's look at an example below, using useState to define a responsive variable name, and a method to change the name setName. When we click the button, the name will change from Xiaoming to Xiaohong

import { useState } from 'react'

function App() {
  const [name, setName] = useState('小明')
  return (
    <>
      <div>名字:{name}</div>
      <button onClick={() => { setName('小红') }} >
        改变名字
      </button>
    </>
  )
}

export default App
复制代码

Why is it defined in this form const [name, setName] = useState('Xiao Ming')?

useState is a function. Calling this function will return an array. What does the returned array contain? This array has two values, the first value is the reactive variable state, and the second value is the function that can change this state. So here is the use of array destructuring assignment. The name of the value returned by useState can be defined by yourself. For example, you can write it as const [name1, changeName1] = useState('Xiao Ming').

As in the example below, without using array destructuring assignment, the code looks less concise.

import { useState } from 'react'

function App() {
  const nameVal = useState('小明')
  const name = nameVal[0]
  const setName = nameVal[1]

  return (
    <>
      <div>名字:{name}</div>
      <button
        onClick={() => {
          setName('小红')
        }}
      >
        修改名字
      </button>
    </>
  )
}

export default App

复制代码

Note: useState can be passed as parameter or not, and the parameter is the initial value of the responsive variable.

define multiple states

import { useState } from 'react'

function App() {
  const [name, setName] = useState('小明')
  const [age, setAge] = useState(18)
  return (
    <>
      <div>名字:{name}</div>
      <div>年龄:{age}</div>
      <button  onClick={() => { setName('小红') }} >
        修改名字
      </button>
      <button onClick={() => { setAge(age+1) }} >
        修改年龄+1
      </button>
    </>
  )
}

export default App
复制代码

Associated variables we can also define in the same object variable state

import { useState } from 'react'

function App() {
  const [info, setInfo] = useState({
    name: '小丁',
    age: 10,
    address: '地球'
  })

  return (
    <>
      <div>名字:{info.name}</div>
      <div>年龄:{info.age}</div>
      <div>地址:{info.address}</div>
      <button
        onClick={() => {
          setInfo({
            ...info,
            age: info.age + 1
          })
        }}
      >
        修改年龄+1
      </button>
    </>
  )
}

export default App

复制代码

This example puts the relevant information in the state variable info, so we use one useState to declare three properties instead of declaring multiple useStates, so the sub-code is cleaner. There is another detail. We only modify one attribute age here, so we can use destructuring assignment to simplify the writing method instead of listing the attributes one by one.

Note: useState Hook to update the state variable always replaces it instead of merging it.

Compared with Class components

You need to define the state responsive variable in the constructor and modify the state through the this.setState method.

import React from 'react'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { name: '小明',age:18 }   //在给构造函数里定义state,值为对象或null
  }
  changeName = (name) => {
    this.setState({ name })        //通过 this.setState修改state,修改是会进行合并的
  }

  render() {
    return (
      <div>
        name:{this.state.name}
        <button onClick={() => { this.changeName('小红') }} >
          修改名字
        </button>
      </div>
    )
  }
}

export default App

复制代码

The last state value is used when modifying the state through this.setState

At this time, you can pass a parameter function to the setState function, and this parameter function can receive two parameters, namely the last state and props. Through these two parameters, you can make new changes according to the last state, and finally return a state object you want to set.

import React from 'react'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      age: 18
    }
  }

  changeAge = () => {
    this.setState(function (state, props) {   //传入一个函数,可以获取到上一次的state,并返回一个对象
      return {
        age: ++state.age
      }
    })
  }

  render() {
    return (
      <div>
        count:{this.state.age}
        <button
          onClick={() => {
            this.changeAge()
          }}
        >
          修改年龄
        </button>
      </div>
    )
  }
}

export default App

复制代码

Compare with Vue

option api

The Vue option api has a special data option for us to define responsive variables. If we want to modify this value, we can directly reassign it, unlike React Hook, which needs to be modified by the method returned by useState.

<template>
  <div>
    <div id="app">名字:{{ username }}</div>
    <button @click="setName">点击改名字</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '小明'
    }
  },
  methods: {
    setName() {
      this.username = '小红'
    }
  }
}
</script>

复制代码

composite api

To define a reactive variable, we need to use ref or reactive. If we want to modify the value, we can directly reassign it.

<template>
 <template>
  <div>ref名字: {{ useName }}</div>
  <button @click="setUserName">点我改变ref名字</button>
  <div>reactive名字: {{ info.name }}</div>
  <button @click="setInfoName">点我改变reactive名字</button>
</template>

<script setup>
import { ref, reactive } from 'vue'

const useName = ref('小明')
function setUserName() {
  useName.value = '小红'
}

const info = reactive({
  name: '小白',
  age: 18
})
function setInfoName() {
  info.name = '大白'
}
</script>

</script>

复制代码

concluding remarks

This article is a personal learning summary. I am very happy if it is helpful to you. If there are any mistakes or suggestions, please point out!

React official website: https://react.docschina.org/

Guess you like

Origin juejin.im/post/7086756714833248286