我們在使用react作為開發(fā)框架的時(shí)候,如果我們使用了redux署鸡,那自然也少不了react和redux的產(chǎn)物--react-redux案糙,那它又暴漏了哪些常用的方法呢?
常用方法
- Provider
- connect
- useSelector
- useDispatch
- useStore
代碼實(shí)現(xiàn)
import React, { useCallback, useContext, useLayoutEffect } from "react"
import { bindActionCreators } from "redux";
// 創(chuàng)建context,用于傳遞store給子組件
const ReactReduxContext = React.createContext();
// Provider提供store注入
const Provider = ({store, children}) =>{
return <ReactReduxContext.Provider value={store}>
{children}
</ReactReduxContext.Provider>
}
// 自定義forceUpdate,返回的是update函數(shù)
const useForceUpdate = () =>{
const [state, setState] = useState(0);
const update = useCallback(()=>{
setState(prev=> prev+1)
}, [])
return update;
}
// 類組件通過connect把state中數(shù)據(jù)注入到props
const connect = (
mapStateToProps = state => state,
mapDispatchToProps
) => WrappedComponent => props =>{
// 通過context取到store
const store = useContext(ReactReduxContext)
const {getState, dispatch, subscribe} = store;
// mapStateToProps是個(gè)函數(shù)靴庆,接收當(dāng)前state,執(zhí)行函數(shù)返回所需state
const stateProps = mapStateToProps(getState())
const dispatchProps = {}
// dispatch可能接受對象或者函數(shù)
if(typeof mapDispatchToProps === 'object'){
// 對象需要用bindActionCreators包裝
dispatchProps = bindActionCreators(mapDispatchToProps, dispatch)
}else if(typeof mapDispatchToProps === 'function'){
// 函數(shù)直接執(zhí)行即可
dispatchProps = mapDispatchToProps(dispatch)
}
const forceUpdate = useForceUpdate();
useLayoutEffect(()=>{
// 監(jiān)聽store變化时捌,強(qiáng)制刷新頁面
const unsubscribe = subscribe(()=>{
forceUpdate()
})
return ()=>{
if(unsubscribe) unsubscribe()
}
},[store])
// 將props,stateProps,dispatchProps一起賦給包裹組件
return <WrappedComponent
{...props}
{...stateProps}
{...dispatchProps}
/>
}
// 函數(shù)式組件中三個(gè)方法:useSelector、useDispatch炉抒、useStore
const useStore = () =>{
const store = useContext(ReactReduxContext)
return store
}
const useSelector = (selector) =>{
const store = useStore()
const {getState, subscribe} = store;
const selectedState = selector(getState())
const forceUpdate = useForceUpdate();
useLayoutEffect(()=>{
const unsubscribe = subscribe(()=>{
forceUpdate()
})
return ()=>{
if(unsubscribe) unsubscribe()
}
},[store])
return selectedState
}
const useDispatch = () =>{
const store = useStore()
return store.dispatch;
}
export {
Provider,
connect,
useSelector,
useDispatch,
useStore,
ReactReduxContext,
}