react-redux知多少?

我們在使用react作為開發(fā)框架的時候,如果我們使用了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是個函數(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ù)式組件中三個方法: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,
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容