整理react hook的使用

491 阅读2分钟

前言

在查阅了网上各位大神关于react hook的分享,自己整理了一部分hook的使用 记录一下防忘

主要内容

git地址 骗小星星专用

自定义hook 实现计数器 可暂停 设置延时

hook基本使用

useContext useReducer 的使用

context实现全局数据共享

模拟实现redux

hook 中使用redux:

插件使用 redux-react-hook

react-redux 直接使用

自定义计数器

function useInterval(Callback: Function, delay: number |null){

    const savedCallback:any = useRef();

    useEffect(() => { 
        savedCallback.current = Callback
    })
   
    
    useEffect(() => {
        function tick() {
            savedCallback.current();
        }
        
        if (delay) {
            let timer = setInterval(tick, delay);
            return () => clearInterval(timer)
        }
    }, [delay])
}

摘自使用 React Hooks 声明 setInterval 里面有详细讲解过程 使用useRef 保存可变值

useReducer useContext 实现数据共享

类型redux全局数据共享 简易实现

index reducer

import UserReducer from './UserList'
import CountReducer from './CountReducer'

// 实现简单的combineReducer 省略各种判断。
const combineReducer = (reducers:any) => {
    return (state:any = {}, action: any) => {        
        return Object.keys(reducers).reduce((nextState:any, key:any) => {
            nextState[key] = reducers[key](state[key], action);
            return nextState;
        },{})
    }
}

const reducers = combineReducer({
    UserReducer,
    CountReducer
})

export default reducers

userList reducer

interface stateType {
    // count: number;
    [index: string]: any;
};

type Action =
    | { type: 'USER_LIST', payload: any }
    | { type: 'USER_ADD', payload: any }
    | { type: 'USER_DELETE', payload: any }

const initalState: stateType = {
    list: [
        {
            name: '用户一',
            desc: '用户一用户一用户一'
        },
        {
            name: '二傻子',
            desc: '二傻子二傻子'
        },
        {
            name: '发的说法',
            desc: '发的是更好范德萨安徽发的是更好范德萨安徽'
        }
    ]
}

const UserReducer = (state: stateType = initalState, action: Action) => {
    switch (action.type){
        case "USER_LIST":
            return state;
        case "USER_ADD":
            return Object.assign({}, state, {list: action.payload});
        case "USER_DELETE":         
            return Object.assign({}, state, {list: action.payload});
        default:
            return state;
    }
}
export default UserReducer

创建 context provider

const initalState: stateType = {count: 0}

export const CombineContext = React.createContext(initalState)


export const CombineProvider = (props: any) => {
    let [state, dispatch] = useReducer(reducers, initalState)
    // redux 中 createStore 会默认执行初始化 createContext可传入初始值 
    
    // 初始化 reducers 中的state值到context 此处需手动初始化
    useEffect(() => {
        dispatch({type: ''})
    },[])
    
    return (
        <CombineContext.Provider value={{state, dispatch}}>
            {props.children}
        </CombineContext.Provider>
    )
}

子组件使用

   const {state, dispatch} = useContext(CombineContext);
   
   function deleteItem (index: number) {
        let list = state.UserReducer.list
        list.splice(index,1)
        dispatch({type: 'USER_DELETE', payload: list})
    }
    

hook 中使用redux:

hook插件使用:

  import { useDispatch, useMappedState } from 'redux-react-hook';
  // 类似于以前 react-redux 中的 connect 函数
    const mapState = useCallback(
        state => ({
            count: state.reduxState.count,
            list: state.reduxState.list
        }),
        []
    )
    
    // 获取redux 数据
    const { count, list } = useMappedState(mapState);

    // 获取 dispatch
    const dispatch = useDispatch();

    const addCount = useCallback(() => {
        dispatch({
            type: 'ADD_COUNT'
        })
    },[dispatch])

react-reudx 也提供了hook支持

import { useSelector, useDispatch, useStore } from 'react-redux';
  const count = useSelector((state: ReduxState) => state.reduxState.count)
    const list = useSelector((state: ReduxState) => state.reduxState.list)
    const store = useStore()
    // console.log(store.getState());
    
    // 获取 dispatch
    const dispatch = useDispatch();

    const addCount = useCallback(() => {
        dispatch({
            type: 'ADD_COUNT'
        })
    },[dispatch])

写在最后

当前整理的hook使用就这么多 大家可根据具体场景使用 希望大家给出更多使用场景的建议 最好附上代码 (空手套代码。。。)