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

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

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


                               ——————————————————————java


useState是什么?

它容许咱们在react函数组件里使用state,能够彻底替代this.state的全部特性。不过,hook只能够用在函数组件里,在类组件里不生效哦react


怎么用useState?

1.  引入useState数组

Import React, { useState } from ‘react’


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

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

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


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

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


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

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


实例操做

场景:ui

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


实现思路:

定义一个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值。

                  

文章结语

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

相关文章
相关标签/搜索