react-redux源码分析

2020-05-09  本文已影响0人  codingQi

react-redux是把reactredux两个库结合起来的一个桥梁。

一、Provider

看的这个版本源码比较新,其中使用了react hook的的API,同时也用到了context来将store向下传递,源码大概梳理如下:

// Context.js

import React from 'react';

// 创建context对象,默认值为null
export const ReactReduxContext = /*#__PURE__*/ React.createContext(null)

if (process.env.NODE_ENV !== 'production') {
    ReactReduxContext.displayName = 'ReactRedux'
}
export default ReactReduxContext;
// Provider.js

import React, { useMemo, useEffect } from 'react';

function Provider({ store, context, children }) {

    const contextValue = useMemo(() => {
        const subscription = new Subscription(store) // Subscription不太懂,不看这两行
        subscription.onStateChange = subscription.notifyNestedSubs

        return { // 只需要知道contextValue返回的是store对象就好了
          store,
          subscription
        }
    }, [store]);

    /**
     * 这一段代码省略,不做讲解,因为Subscription不太懂,后面懂了再回过头来看
     */
    const previousState = useMemo(() => store.getState(), [store])
    useEffect(() => {
        const { subscription } = contextValue
        subscription.trySubscribe()

        if (previousState !== store.getState()) {
            subscription.notifyNestedSubs()
        }
        return () => {
            subscription.tryUnsubscribe()
            subscription.onStateChange = null
        }
    }, [contextValue, previousState]);


    // 使用React.createContext创建的Context
    const Context = context || ReactReduxContext 

    // 说明react-redux中的`Provider`顶层组件其实也就是`Context.Provider`
    return <Context.Provider value={contextValue}>{children}</Context.Provider>
}
export default Provider;

主要原理就是使用了Context来实现传递的,在项目中的使用方式如下:

import React from 'react';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import ReactDom from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import storeTree from './store';

const store = createStore(storeTree, applyMiddleware(thunk));
ReactDom.render(
    <Provider store={store}>
        <LocaleProvider locale={zhCN}>
            // ...
        </LocaleProvider>
    </Provider>,
    document.getElementById('app')
);

按理来说,后面的组件应该都能使用this.context拿到上面contextValue的值,即store的值。

由于目前对context还不太了解,后面需要学习使用下context才能对这个问题更加肯定。

我在crm-manage这个项目里试了下在页面里获取props,但是结果里没有context这个字段,也不知道为什么,猜想是因为版本比较低的原因或者是嵌套的原因导致,反正目前不能确定,也不想在这个老项目里去试。

后面在新的项目里或者在我自己的脚手架里试试,用一下context

二、connect

这个就比较复杂了,用的最多的就是用作容器组件来将storeaction都放进props里,后面直接从props里获取使用就行。

前面在redux里的bindActionCreators已经提过connect,其实我们都知道connect就是一个高阶组件(HOC),那我们现在就来看看这个高阶组件的源码实现,以及传入的mapStateToProps(state)mapDispatchToProps(dispatch)的入参为什么要这样定义?

const mapStateToProps = (state) => state; // 返回的state是对象
const mapDispatchToProps = (dispatch) => { // 返回对象
    action1: (params) => {
        dispatch(action1(params))
    },
    actionNew: (params) => {
        dispatch(action2(params))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
上一篇下一篇

猜你喜欢

热点阅读