React Event Hooks
背景
在开发中, 往往会需要跨组件传递数据或事件, 而且有时候需要按顺序依次调用, redux不是很好实现, 而react里实现这种跨组件的数据传递的就是使用context, 可以使用context来实现一个事件处理组件, 同时, 为了这个事件处理组件能够在redux里使用, 可以将这个组件绑定到store上
开发
ReduxEventContext
提供默认的context内容
1  | import { createContext } from 'react';  | 
ReduxEventProvider
提供封装好的Provider节点, 将事件处理方法绑定到组件上
1  | import React, { useMemo } from 'react';  | 
storeEnhancer
封装createStore的增强方法, 给store注入事件处理代码
1  | import _ from 'lodash';  | 
createStore
使用上面的storeEnhancer创建store
1  | const store = createStore(rootReducer, compose(applyMiddleware(thunk), applyEventBus(events)));  | 
useEventBus
使用ReduxEventContext来传递事件处理方法
1  | import { useContext } from 'react';  | 
使用
添加事件监听
在需要加上事件监听的组件里, 注册对应的事件监听函数即可
1  | import React, { useEffect, useRef } from 'react';  | 
在组件中使用
1  | const { emit, events } = useEventBus();  | 
在reducer中使用
1  | const loadData = () => async (dispatch, getState) => {  | 
React Event Hooks

