【开始学习React Hook(1)】Hook之useState

539 阅读4分钟

react hook是react推出的一种特殊函数。这些函数可以让你在不创建react class的情况下依然可以使用react的一些特性(诸如目前react的钩子函数拥有的所有特性)。

最常用的hook有useState, useEffect, 日常开发使用这两个就足够了。如果再懂点useReduer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue ,自定义hook,就再好不过了。


                               ——————————————————————


useState是什么?

它允许我们在react函数组件里使用state,可以完全替代this.state的所有特性。不过,hook只可以用在函数组件里,在类组件里不生效哦


怎么用useState?

1.  引入useState

Import React, { useState } from ‘react’


2. 在函数组件里声明state属性

const [ xx, setXx ] = useState(xx的初始值);

useState方法接受的唯一参数,就是xx的初始值。


3. 在函数组件里想要读取state属性

函数组件里没有this,读取state属性是直接读取xx


4. 在函数组件里想更新state属性

直接使用setXx( xx的更新值) 即可更新xx的值,setXxx()的参数既可以是一个更新后的值,也可以为一个传了旧的xx值的函数。格式为:
 setXx((preState)=>return { ...preState, curState})


实例操作

场景:

某个文档文字过长,点击“查看更多”按钮文档会全部展示出来,点击“收起”按钮,文档会收起一部分。


实现思路:

定义一个state属性fold,类型为boolean,当展示”收起”按钮时,fold值为true;点击可切换成“查看更多”,fold值也会变为false;


实现代码:

使用react 类组件实现如下:

import React, {Component} from 'react';

class HookExample extends Component {
  constructor(props){
    super(props);
    this.state = {
      fold: true,
    }
  }

  render() {
    const { fold } = this.state;
    return (
    <div className="hook-example">
      <article>
        <header>
          <h2>Life</h2>
        </header>
        <section className={fold ? 'fold' : 'unfold'}>
          <p>  If life is a river, it is the most exciting section.</p>
          <p>  Flowing a trickle of childhood, life began to restlessness, 
          personality spray, a piece after piece of Pentium the melody of youth。
          It is surging, it's always a time of the wild and intractable, slap embankment, heaving ship of life。</p>
        </section>
      </article>
      <span onClick={()=>{this.setState({fold: !fold})}}>{fold ? '查看更多' : '收起'}</span>
    </div>);
  }
}

export default HookExample;

使用hook函数组件实现如下:

import React, {useState} from 'react';
function HookExample(){
  const [fold, setFold] = useState(true);
  return (
  <div className="hook-example">
     <article>
        <header>
           <h2>Life</h2>
        </header>
        <section className={fold ? 'fold' : 'unfold'}>
           <p> If life is a river, it is the most exciting  section.</p>
           <p> Flowing a trickle of childhood, life began to  restlessness,
           personality spray, a piece after  piece of  Pentium the melody of youth。 
           It is  surging, it's always  a time of the wild and  intractable, slap embankment, 
           heaving ship of  life。</p>
        </section>
     </article>
     <span onClick={()=>{setFold(!fold)}}>{fold ? '查看更 多' : '收起'}</span>
  </div>
 );
}
export default HookExample;

页面效果:



实现步骤详解:

第一步:创建组件,声明state属性  

使用react类组件可以这样实现:

import React, {Component} from 'react';
class HookExample extends Component {
constructor(props){
  super(props);
  this.state = {
    fold: true,
  }
}

而用useState,只需:

import React, {useState} from 'react';
function HookExample(){
const [fold, setFold] = useState(true);

useState只接收一个参数,就是该state属性的初始值。它会返回一个数组,里面包含两个值,通过数组解构的方式将第一个值赋给用户定义的state属性(即fold),第二个值为state属性的更新函数,赋给用户定义的属性更新函数(setFold)。

const [ fold, setFold ] = useState(true) 
// 等同于
const result = useState(true);
const fold = result[0];
const setFold = result[1];

第二步:读取state属性

在react 类组件里,我们需要这样:

const { fold } = this.state;
<section className={fold ? 'fold' : 'unfold'}>

在使用了hook的函数组件里,我们只需:

<section className={fold ? 'fold' : 'unfold'}>

类组件里,我们需要通过this.state读取到fold的值。而在函数组件里,直接使用fold即可。

第三步: 更新state属性

react组件里,如下:

<span onClick={()=>{ this.setState({fold: !fold}) }}>{fold ? '查看更多' : '收起'}</span>

在函数组件里,如下:

<span onClick={()=>{setFold(!fold)}}>{fold ? '查看更多' : '收起'}</span>

在类组件里,通过调用setState更新fold,更新后的fold会与当前的state对象进行合并。

而在函数组件里,直接调用第一步声明的更新函数setFold即可更新fold的值,fold值更新后,react会重新渲染HookExample组件,并把最新的fold值传给它。


使用小提示

在实际开发中,我们可能需要多个state属性。你可以写多个useState

const [A1, setA1] = useState('');
const [A2, setA2] = useState(true);

如果state属性直接有业务关联,那么可以把这几个state属性合在一起,用一个useState即可。

const [A, setA] = useState({
   A1: ‘’,
   A2: true
});

与react类组件不同的是,当我们更新属性A时,会完全替代之前的A值,而不是merge原来的A值。

                  

文章结语

谢谢您读完我的文章,文章的内容全是本人的手记,一是方便自己查看,二来分享给众多和我一样热爱前端的小伙伴。文中若有瑕疵疏漏之处,望各位大佬留言指出,谢谢~