hooks 系列二:useState

快來加入咱們吧!

"小和山的菜鳥們",爲前端開發者提供技術相關資訊以及系列基礎文章。爲更好的用戶體驗,請您移至咱們官網小和山的菜鳥們 ( xhs-rookies.com/ ) 進行學習,及時獲取最新文章。css

"Code tailor" ,若是您對咱們文章感興趣、或是想提一些建議,微信關注 「小和山的菜鳥們」 公衆號,與咱們取的聯繫,您也能夠在微信上觀看咱們的文章。每個建議或是贊同都是對咱們極大的鼓勵!前端

前言

這篇文章,咱們主要目的是瞭解一下 狀態鉤子(useState) 的使用.java

useState

定義

useState() 用於爲函數組件引入狀態。純函數不能有狀態,因此使用鉤子來引入狀態。react

如何使用

useState 的使用以下面的語句。web

const [count, setCount] = useState(defaultValue) // 假設 defaultValue 爲 0
複製代碼
let countVariable = useState(0)
let count = countVariable[0]
let setCount = countVariable[1]
複製代碼
setCount(count + 1) // count 1
setCount(10) // count 10
複製代碼
const [name, setName] = useState('xhs')
const [age, setAge] = useState(18)
const [dowhat, setDowhat] = useState({ thing: 'Learn Hooks' })
複製代碼
setName('xxxxxxxhs')
setAge(20)
setDowhat({ thing: 'Learn Nothing' })
複製代碼
import React, { Component } from 'react'
import './App.css'export class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 0,
    }
  }
  handleWithAddOne() {
    this.setState({ count: this.state.count + 1 })
  }
  handleWithAddTwo() {
    this.setState({ count: this.state.count + 2 })
  }
  handleWithDecreaseOne() {
    this.setState({ count: this.state.count - 1 })
  }
  render() {
    const { count } = this.state
    return (
      <div className="app">        <p>Now,the number is {count}.</p>        <div className="three-btn">         {/* 點擊以後 count + 1 */}          <button className="button add" onClick={() => this.handleWithAddOne()}>           Click it, the number will add 1          </button>         {/* 點擊以後 count + 2 */}          <button className="button add" onClick={() => this.handleWithAddTwo()}>           Click it, the number will add 2          </button>         {/* 點擊以後 count - 1 */}          <button className="button decrease" onClick={() => this.handleWithDecreaseOne()}>           CLick it, the num will decrease 1          </button>        </div>      </div>
    )
  }
}
複製代碼
.app {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.three-btn {
  display: flex;
  flex-direction: column;
}
​
.button {
  height: 40px;
  margin: 12px 0px;
  color: white;
  border: none;
  border-radius: 10px;
}
.add {
  background-color: #1890ff;
}
​
.decrease {
  background-color: red;
}
複製代碼

useState-gif.gif

使用多個 useState 就能夠定義多個 state 變量。數組

useState 返回的是一個數組,通常直接使用解構賦值取出兩個值,state 以及 修改 state 的函數 。這兩個值是須要成對獲取的。微信

useState 函數,只須要傳入一個惟一參數,做爲默認值,初始化 statemarkdown

如今,讓咱們來總結一下 useStateapp

小結

簡單來說,useState 就是爲函數組件提供了 React state 的功能,如今就能夠稱爲函數組件了,這以前,叫作無狀態組件函數

就這樣,咱們就成功使用了 useState ,運行的結果與上面類組件的運行結果是相同的,代碼的複雜程序被大幅度的下降了,相比於類組件,可能這樣的方式更容易讓人接受。

import './App.css' // 導入css樣式,樣式同上
import { useState } from 'react'

function App() {
  const [count, setCount] = useState(0)
  return (
    <div className="app"> <p>Now,the number is {count}.</p> <div className="three-btn"> <button className="button add" onClick={() => setCount(count + 1)}> Click it, the number will add 1 </button> <button className="button add" onClick={() => setCount(count + 2)}> Click it, the number will add 2 </button> <button className="button decrease" onClick={() => setCount(count - 1)}> CLick it, the num will decrease 1 </button> </div> </div>
  )
}
複製代碼

咱們來完成需求:

咱們將 state 的值,使用 useState 進行建立,用 setCount 進行修改 count 的值。

使用 useState 重寫案例

下面,咱們一塊兒來看看 useState 是怎麼實現的。

從上面咱們能夠看到,雖然效果已經達到是咱們指望,可是能夠很明顯的感覺到它的代碼是很"重"的,在咱們真實的項目開發中,React App 都是由多個類,按照層級,一層層組成的,複雜程度可想而知。這時候,若是咱們在加入 Redux ,那會變得更加複雜繁瑣。

這是運行以後的效果圖

css 的樣式

首先,咱們來看一下,在類組件中,咱們使用 state 的狀況,咱們須要在 state 中聲明變量 count,並賦予默認值 0,而修改的方式只有經過 this.setState()count 進行修改。

類組件使用 this.state 實現

我想要有一個簡單的計數器,須要有 +1+2-1 三個操做,能夠刷新頁面中如今的 numer 值。

如今你以及對 useState 有了必定的瞭解,那咱們就來完成一個需求:

對比類組件

如何修改這些變量呢?跟上面同樣,直接調用各自的 set 方法就能夠了。

上述的語句只能聲明一個 state 變量,若是你想要聲明多個 state 變量,只須要使用多個 useState 就能夠了。

使用多個 state 變量

首先執行第一次 setCount 以後,值從 0 -> 1 ,第二次執行的時候,直接傳入了一個 10,而它的值就直接從 1 -> 10 因此 count 的值更新爲 10

修改 state 的值,只須要直接使用 setCount 方法就能夠進行更改。傳入的值會直接返回給 count 值並更新。以下面兩個。

修改 state

也就是說,使用 useState 返回的是一個數組,它等價於下面的代碼:

返回的是一個數組,可是都會被使用 JavaScript 語法的數組解構成兩個值,當前 state修改 state 的函數 。這與 class 裏面 this.state.countthis.setState 相似,惟一區別就是你須要成對的獲取它們。

useState 返回值

它定義了一個名爲 countstate 變量,它與 class 裏面的 this.state 提供的功能徹底相同。通常來講,在函數退出後變量就會」消失」,而 state 中的變量會被 React 保留。

useState 作了什麼

useState 須要傳入的惟一參數就是初始化 state ,咱們能夠傳各類類型的值,好比:數字、字符、數組、對象等。

useState 須要的參數

下節預告

在下節中,咱們將爲你們介紹 useEffect ,敬請期待!

相關文章
相關標籤/搜索