1. 程式人生 > >React-redux原始碼解析

React-redux原始碼解析

  • Provider

       //最後匯出的是createProvider()。所以一開始storeKey應該是以預設值‘store’傳進去的
       function createProvider(storeKey = 'store', subKey) {
       const subscriptionKey = subKey || `${storeKey}Subscription`
    
       class Provider extends Component {
           //設定context,能讓子元件拿到store
           //相當於返回 {store: this.store}
           getChildContext() {
             return { [storeKey]: this[storeKey], [subscriptionKey]: null }
           }
    
           constructor(props, context) {
             super(props, context)
             //this.store = props.store
             this[storeKey] = props.store;
           }
    
           render() {
             //只能有一個子元件
             return Children.only(this.props.children)
           }
       }
       
       //props和context型別驗證
       Provider.propTypes = {
           store: storeShape.isRequired,
           children: PropTypes.element.isRequired,
       }
       Provider.childContextTypes = {
             [storeKey]: storeShape.isRequired,
            [subscriptionKey]: subscriptionShape,
        }
    
            return Provider
    }

通常的做法是我們先通過redux建立好store,然後賦給Provider元件的store屬性。在Provider元件內部,拿到這個store,設定為context屬性,這樣就能讓它的所有元件都能通過context拿到store。

   <Provider store={store}>
       <App />
   </Provider>