Hook the use of react

1 Review

2、Hook

react 16.8.0 version appears

It allows you to use the state as well as other React characteristics without writing class is.

(With use state class components, functional components using stateless)

Functional components can also write state

Hook uses a closure mechanism of JavaScript

2.1 useState Hook ----- functional assembly set state

import React, { useState } from 'react';

const Home = () => {
  // 声明一个新的叫做 “count” 的 state 变量
  // 设置初始化数据为0, 改变count的函数为setCount
  const [ count, setCount ] = useState(0)
  const [ list, setList ] = useState([1, 2, 3, 4])
  return (
    <div>
      <button onClick= { () => {
        let num = count + 1
        setCount(num)
      }}>加1</button>
      { count }
      <button onClick= { () => {
        setList([5,6,7,8])
      }}>改变list</button>
      { 
        list.map((item, index) => (
          <p key = { index }> { item } </p>
        ))
      }
    </div>
  )
}

export default Home;

2.2 useEffect

Tell React components need to perform certain operations after rendering.

React function will save you pass (we call it "effect"), and call it after the execution of DOM updates.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
// useEffect 其实是 componentDidMount + componentDidUpdate + componentWillUnmount

const Home = () => {
  const [ bannerlist, setBannerlist ] = useState([])

  useEffect(() => {
    axios.get('/api/banner').then(res => {
      setBannerlist(res.data.data)
      // console.log(bannerlist)
    })
  })

  const [ prolist, setProlist ] = useState([])

  useEffect(() => {
    axios.get('/api/pro').then(res => {
      setProlist(res.data.data)
    })
  })

  return (
    <div>
      轮播图列表
      {
        bannerlist.map(item => (
          <p key = { item.bannerid }>
            { item.img }
          </p>
        ))
      }
      {
        prolist.map(item => (
          <p key = { item.proid }>
            { item.proname }
          </p>
        ))
      }
    </div>
  )
}

export default Home;

2.3 each execution control effect

useEffect(() => {}, [count])
useEffect(() => {}, [])

2.4 Hook rule

Hook only at the top level

Hook called only function in React

ESLint plug

import React, { useState, useEffect } from 'react';
import axios from 'axios';

// 自定义HOOK
const useLoginState = () => {
  const [loginstate, setLoginstat] = useState('no')
  useEffect(() => {
    if (localStorage.getItem('loginstate') === 'ok') {
      setLoginstat('ok')
    } else {
      setLoginstat('no')
    }
  }, [loginstate])
  return loginstate
}

const Home = () => {
  const loginstate = useLoginState()

  return (
    <div>
      自定义HOOK
      {
        loginstate === 'ok' ? <p>登陆了</p> : <p>未登录</p>
      }
    </div>
  )
}

export default Home;

Guess you like

Origin www.cnblogs.com/hy96/p/11916848.html