当我们使用redux进行数据管理的时候,一般都是在根组件通过Provider的方式引入store,然后在每个子组件中,通过connect的方式使用高阶组件进行连接,这样造成的一个问题是,大量的高阶组件代码冗余度特别高,既然hooks带来了新特性,不如一起来用用看

目录结构如下:

  • action/example/index.js:
    我们还使用redux的思想,编写action
  • reducer/example/index.js:
    处理action,不同于redux的reducer,这里我们可以不用提供初始状态
  • 根组件App.js:
    Provider提供给子组件context
    useReducer定义的位置,引入一个reducer并且提供初始状态initialState
  • 子组件component/example/example.js:
    useContext定义的位置,获取祖先组件提供的context
    useEffect用于进行异步请求
  • 1.reducer/example/index.js

    import * as Types from '../../types/types';
    export const defaultState = {
        count: 0
    export default (state, action) => {
        switch(action.type) {
            case Types.EXAMPLE_TEST:
                return {
                    ...state,
                    count: action.count
            default: {
                return state
    

    2.action/example/index.js

    import * as Types from '../../types/types';
    export const onChangeCount = count => ({
        type: Types.EXAMPLE_TEST,
        count: count + 1
    

    3.根组件App.js

    import React, { useReducer } from 'react';
    import Example from './test/example';
    import example, { defaultState } from './reducer/example';
    export const ExampleContext = React.createContext(null);
    const App = () => {
    	const [exampleState, exampleDispatch] = useReducer(example, defaultState);
    	return (
    		<ExampleContext.Provider value={{exampleState, dispatch: exampleDispatch}}>
    			<Example />
    		</ExampleContext.Provider>
    export default App;
    

    4.子组件component/example/example.js

    import React, { useState, useEffect, useReducer, useContext } from 'react';
    import actions from '../../action';
    import { ExampleContext } from '../../App';
    const Example = () => {
        const exampleContext = useContext(ExampleContext);
        useEffect(() => {
            window.document.title = `you click ${exampleContext.exampleState.count} times`;
        }, [exampleContext.exampleState.count]);
        return (
                <p>you can click it</p>
                <button onClick={() => exampleContext.dispatch(actions.onChangeCount(exampleContext.exampleState.count))}>click it</button>
    export default Example;
    

    5.types/types.js

    export const EXAMPLE_TEST = 'EXAMPLE_TEST';
    

    使用useContext()时候我们不需要使用Consumer了。但不要忘记export和import上下文对象