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 ,敬请期待!

相关文章
相关标签/搜索