运用react hooks完成本身的context-redux

首发自我的github博客,迎接star

注:如要运转本文的代码,请先确认本身的react版本已支撑hooks

react hooks出来已经有段时刻了,本文不对hooks的详细用法作引见,而是运用hooks完成一个浅易的基于context的redux

运用useReducer完成第一版redux

React hooks自带了useReducer供我们运用,它接收两个参数,一是reducer函数,二是初始state,并返回state和dispatch函数,以下

const [state, dispatch] = useReducer(reducer, initialState); 

这个函数本身完成的话也不难,以下:

const useMyReducer = (reducer, initialState) => {
    const [state, setState] = useState(initialState);
    const dispatch = action => {
        const newState = reducer(action, state);
        setState(newState);
    };
    return [state, dispatch];
};

行将initialState作为state的初始状况传入useState,dispatch则是一个函数,它会将接收的action和state传给reducer,并猎取reducer的返回值赋给state

我们先应用useReducer完成一个计数器的简朴页面

reducer函数和initialState以下:

const initialState = {
    count: 0
};

const reducer = (state, action) => {
    switch (action.type) {
        case "increase":
            return { ...state, count: state.count + 1 };
        case "decrease":
            return { ...state, count: state.count - 1 };
        default:
            return state;
    }
};

计数器组件:

const Demo = () => {
    const [state, dispatch] = useReducer(reducer, initialState); 
    return (
        <div>
            counter:{state.count}
            <div>
                <button
                    onClick={() => {
                        dispatch({ type: "increase" });
                    }}
                >
                    increase
                </button>
                <button
                    onClick={() => {
                        dispatch({ type: "decrease" });
                    }}
                >
                    decrease
                </button>
            </div>
        </div>
    );
};

这就是第一版的redux了,但这个redux有些题目,就是它的state和dispatch是属于本身的,其他组件并不能拿到,也就是说,假如我们的页面有两个Demo组件,它们的state是各自自力,互不影响的

将state和dispatch存在context中

为了处置惩罚上述题目,我们必需具有一个全局状况,并将state和dispatch放入这个全局状况中。这里,我们选用context作为我们的全局状况,context在旧版React中不引荐运用,但在革新以后,官方最先引荐人人运用

我们先建立一个context:

const context = React.createContext();

为了各个组件都能拿到context的数据,我们须要有一个Provider组件包在最外层:

const Provider = props => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <context.Provider value={{ state, dispatch }}>
            {props.children}
        </context.Provider>
    );
};

我们将useReducer返回的state、dispatch传入context.Provider中,让它的children都能拿到

然后,我们像下面一样用Provider包在组件外层:

<Provider>
    <Demo />
    <Demo />
</Provider>

我们删去计数器Demo组件中的:

const [state, dispatch] = useReducer(reducer, initialState); 

加上经由过程useContext函数拿到context上的数据:

const { state, dispatch } = useContext(context);

要注意的是,传入useContext函数的context必需是我们之前经由过程React.createContext()建立的context

如许,即使是两个Demo组件,它们也是共用一份数据了

处置惩罚异步的题目

很显然,如今的context-redux和纯真的redux一样,只能dispatch一个对象,也就是说,这个dispatch操纵是同步的,假如我们要做异步的操纵呢?很简朴,我们自创redux-thunk的要领,让dispatch能够接收函数参数

革新Provider函数组件以下:

const Provider = props => {
    const [state, origin_dispatch] = useReducer(reducer, initialState);
    const dispatch = action => {
        if (typeof action === "function") {
            return action(origin_dispatch);
        }
        return origin_dispatch(action);
    };
    return (
        <context.Provider value={{ state, dispatch }}>
            {props.children}
        </context.Provider>
    );
};

我们将userReducer函数返回的原始dispath命名为origin_dispatch,自定义dispatch函数,当action为函数的时刻,我们实行action函数,并将origin_dispatch看成参数传进去;action不是函数,直接挪用origin_dispatch,不做处置惩罚

我们测试一下:

const sleep = wait => {
    return new Promise(resolve => {
        setTimeout(() => resolve(), wait);
    });
};
const increaseCount = async dispatch => {
    await sleep(1000);
    dispatch({ type: "increase" });
};
<button
    onClick={() => {
        dispatch(increaseCount);
    }}
    >
    increase
</button>

increaseCount是一个异步函数,我们将它看成参数传入我们封装的新dispatch中,点击increase按钮,1s以后,计数器的数字加1,至此,我们的context-redux也支撑dispatch异步操纵了

末了

本文的代码,我放在了本身的github上,这是传送门

    原文作者:Bowen
    原文地址: https://segmentfault.com/a/1190000018345798
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞