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