6

hooks 系列二:useState

 3 years ago
source link: https://segmentfault.com/a/1190000040380349
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

快来加入我们吧!

"小和山的菜鸟们",为前端开发者提供技术相关资讯以及系列基础文章。为更好的用户体验,请您移至我们官网小和山的菜鸟们 ( https://xhs-rookies.com/ ) 进行学习,及时获取最新文章。

"Code tailor" ,如果您对我们文章感兴趣、或是想提一些建议,微信关注 “小和山的菜鸟们” 公众号,与我们取的联系,您也可以在微信上观看我们的文章。每一个建议或是赞同都是对我们极大的鼓励!

我们为什么要学 hooks

这篇文章,我们主要目的是了解一下 状态钩子(useState) 的使用.

useState

useState() 用于为函数组件引入状态。纯函数不能有状态,所以使用钩子来引入状态。

useState 的使用如下面的语句。

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 函数,只需要传入一个唯一参数,作为默认值,初始化 state

现在,让我们来总结一下 useState

简单来讲,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 ,敬请期待!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK