export default connect( state => ({ counter: state.counter }), )(Counter); connect方法詳解: 首先將它改寫成爲普通函數的寫法: export default connect(function(state){ //這裏的參數state就是connect接收的外部傳入的state. //connect方法接受兩個參數:mapStateToProps和mapDispatchToProps,而這裏的參數state實際是mapStateToProps的參數 return( counter: state.counter //這裏是創建一個從(外部的)state對象到(UI 組件的)props對象的映射關係
//這裏的state是怎麼來的呢?<Provider store={store}>從這裏來的,provider接受參數Store,而且讓Store對子組件可用.這時候 裏面的子組件才能夠使用方法關聯store。 // state.counter 裏的counter是怎麼來的呢?是從reducer文件內引入的。 ); })(Counter); //這個Counter是 UI 組件,export default的內容就是由 React-Redux 經過connect方法自動生成的容器組件<Provider>connect
connect方法生成容器組件之後,須要讓容器組件拿到state對象,才能生成 UI 組件的參數。
React-Redux 提供Provider組件,能夠讓容器組件拿到state。
Provider在根組件外面包了一層,這樣一來,App的全部子組件就默認均可以拿到state了,store放在了上下文對象context上面。而後,子組件就能夠從context拿到storeide