使用React Hooks新特性useReducer、useContext替代传统Redux高阶组件案例

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

目录结构如下:
1616136-20190416104945923-1975496319.png

  • 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 (
        <div>
            <p>you can click it</p>
            <button onClick={() => exampleContext.dispatch(actions.onChangeCount(exampleContext.exampleState.count))}>click it</button>
        </div>
    )
}

export default Example;

5.types/types.js

export const EXAMPLE_TEST = 'EXAMPLE_TEST';

总结

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

转载于:https://www.cnblogs.com/fe-linjin/p/10715524.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值