美文网首页
React Hooks && Hox

React Hooks && Hox

作者: mwj610 | 来源:发表于2020-10-23 14:14 被阅读0次

一、React Hooks

1.useState状态钩子

import React,{useState} from 'react';
import './App.css';

function App() {
    const [count,setCount] = useState(0)
    const addNum = () => {
        setCount(count + 10)
    }
    return (
        <div>
            <div>{count}</div>
            <button onClick={addNum}>点击+1</button>
        </div>
    )
}
export default App;

const [count,setCount] = useState(0)
useState创造一个状态,赋值一个初始值,当前赋值的初始值为0
数组的第一个是一个变量,此变量指向当前状态的值,相当于this.state
数组的第二个是一个函数,此函数可以修改状态的值,相当于this.setState

2.useContext共享状态钩子

import React,{useContext} from 'react';
import './App.css';

function App() {
    const AppContext = React.createContext()

    const Achild = () => {
        const {name} = useContext(AppContext)
        return (
            <div>组件A:{name}</div>
        )
    }

    const Bchild = () => {
        const {name} = useContext(AppContext)
        return (
            <div>组件B:{name}</div>
        )
    }

    return (
        <AppContext.Provider value={{name:'mwj'}}>
            <Achild/>
            <Bchild/>
        </AppContext.Provider>
    )
}
export default App;

3.useReducer钩子函数

import React,{useReducer} from 'react';
import './App.css';

function App() {

    const reducer = (state,action) => {
        const actionFn = {
            add:function () {
                return {
                    ...state,
                    count:state.count+1
                }
            }
        }
        return actionFn[action.type]()
    }

    const [state,dispatch] = useReducer(reducer,{count:0})

    const addCount = () =>{
        dispatch({
            type:'add'
        })
    }

    return (
        <div>
            <div>{state.count}</div>
            <button onClick={addCount}>点击+1</button>
        </div>
    )
}
export default App;

根据action的类型去执行对应的函数修改state

4.useEffect()副作用钩子

import React,{useEffect,useState} from 'react';
import './App.css';

function App() {
    const [loading,setLoading] = useState(true)

    useEffect(()=>{
        setTimeout(() => {
            setLoading(false)
        },3000)
    })
    return (
        loading?<div>loading...</div>:<div>加载完成</div>
    )
}
export default App;
  • useEffect()相当于componentDidmount
  • 第一个参数是回调函数,第二个参数是数组
  • 当没有第二个参数时,每次渲染之后都会执行回调函数
import React,{useEffect,useState} from 'react';
import './App.css';

function AsyncPage({name}) {
    const [loading,setLoading] = useState(true)
    const [person,setPerson] = useState({})

    useEffect(() => {
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
            setPerson({name})
        },3000)
    },[name])
    return () => {
            console.log("组件被卸载了")
        }
    return (
        loading?<div>Loading...</div>:<div>{person.name}</div>
    )
}
function App() {
    const [name,setName] = useState('mwj')
    const [show,setShow] = useState(true)
    const changeName = (name) => {
        setName(name)
    }

    return(
        <div>
            {show ? <AsyncPage name={name}/> : <div>组件已卸载</div>}
            <AsyncPage name={name}/>
            <button onClick={() => changeName('小王')}>将名字改成小王</button>
            <button onClick={() => changeName('小李')}>将名字改成小李</button>
            <button onClick={() => setShow(false)}>卸载组件</button>
        </div>
    )
}
export default App;
  • 当有第二个参数时,回调函数会依据数组的发生变化而调用
  • useEffect的返回函数,可作为卸载的生命周期函数

5.自定义钩子函数

function usePerson(name) {
    const [loading,setLoading] = useState(true)
    const [person,setPerson] = useState({})

    useEffect(() => {
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
            setPerson({name})
        },3000)
        return () => {
            console.log("组件被卸载了")
        }
    },[name])
    return [loading,person]
}

function AsyncPage({name}) {
   const [loading,person] = usePerson(name)
    return (
        loading?<div>Loading...</div>:<div>{person.name}</div>
    )
}
  • 根据业务需求,将自己组装的钩子函数封装成一个函数,返回对应需要的状态和修改状态的方法即可

二、Hox

hox 是完全拥抱 React Hooks 的状态管理器,model 层也是用 custom Hook 来定义的,它有以下几个特性:

  • 只有一个 API,简单高效,几乎无需学习成本
  • 使用 custom Hooks 来定义 model,完美拥抱 React Hooks
  • 完美的 TypeScript 支持
  • 支持多数据源,随用随取

1.安装npm install --save hox
2.举例:
比如你开始的代码是这样的:

const CountApp = () => {
 const [count, setCount] = useState(0)
 const decrement = () => setCount(count - 1)
 const increment = () => setCount(count + 1)

 return (
   <div>
     count: {count}
     <button onClick={increment}>自增</button>
     <button onClick={decrement}>自减</button>
   </div>
 )
}

如果你想持久化数据,每次进来想恢复上一次的 count,把逻辑代码复制出来,用 createModel 包一层就完事了。

import { createModel } from 'hox';

/* 逻辑原样复制过来 */
function useCounter() {
  const [count, setCount] = useState(0);
  const decrement = () => setCount(count - 1);
  const increment = () => setCount(count + 1);
  return {
    count,
    decrement,
    increment
  };
}
/* 用 createModel 包一下就行 */
export default createModel(useCounter)
import { useCounterModel } from "./useCounterModel";

export function CountApp() {
  const {count, increment, decrement} = useCounterModel();
  return (
    <div>
      count: {count}
      <button onClick={increment}>自增</button>
      <button onClick={decrement}>自减</button>
    </div>
  )
}

使用hox就是这么简单,通过createModel包装一下将custom hook变成share hook,就可以在各个组件之间共享数据状态,并实现逻辑封装和复用。

相关文章

  • React Hooks && Hox

    一、React Hooks 1.useState状态钩子 const [count,setCount] = use...

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • React Hooks

    前言 React Conf 2018 上 React 提出了关于 React Hooks 的提案,Hooks 作为...

  • 5分钟简单了解React-Hooks

    首先附上官网正文?:React Hooks Hooks are a new addition in React 1...

  • react-hooks

    react-hooks react-hooks 是react16.8以后,react新增的钩子API,目的是增加代...

  • React-hooks API介绍

    react-hooks HOOKS hooks概念在React Conf 2018被提出来,并将在未来的版本中被...

  • React Hooks 入门

    React Hooks 是 React v16.8 版本引入了全新的 API。 React Hooks 基本概念 ...

  • react hooks 源码分析 --- useState

    1. react hooks简介 react hooks 是react 16.8.0 的新增特性,它可以让你在不编...

  • React Hooks的入门简介

    什么是React Hooks? 首先React Hooks是React生态圈里的新特性,它改变了传统react的开...

网友评论

      本文标题:React Hooks && Hox

      本文链接:https://www.haomeiwen.com/subject/fffvmktx.html