react-redux中有兩大核心方法
- connect
- Provider
本文要說(shuō)的是Provider,connect請(qǐng)看這里
Provider的作用
- Provider是作為整個(gè)App的容器攻人,在你原有的App Container的基礎(chǔ)上再包上一層
- 接受
Redux
的store作為props
照宝,并將其聲明為context
的屬性之一 - 子組件可以在聲明了
contextTypes
之后可以方便的通過(guò)this.context.store
訪問(wèn)到store
Provider源碼分析
// Provider 依賴react裂垦,導(dǎo)入react中元素
import { Component, PropTypes, Children } from 'react'
// 導(dǎo)入store驗(yàn)證規(guī)則以及警告提示方法
import storeShape from '../utils/storeShape'
import warning from '../utils/warning'
// 標(biāo)識(shí)是否已經(jīng)收到警告
let didWarnAboutReceivingStore = false
// 此方法主要用來(lái)警告當(dāng)前的對(duì)象是否和傳入的對(duì)象相同
function warnAboutReceivingStore() {
if (didWarnAboutReceivingStore) {
return
}
didWarnAboutReceivingStore = true
warning(
'<Provider> does not support changing `store` on the fly. ' +
'It is most likely that you see this error because you updated to ' +
'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' +
'automatically. See https://github.com/reactjs/react-redux/releases/' +
'tag/v2.0.0 for the migration instructions.'
)
}
// Provider是一個(gè)內(nèi)部組建
export default class Provider extends Component {
// 構(gòu)造方法傳入props和context
constructor(props, context) {
super(props, context)
this.store = props.store
}
// 返回從構(gòu)造方法傳遞的store迫淹,將store傳遞給子孫component
getChildContext() {
return { store: this.store }
}
// 返回僅有的一個(gè)子元素,否則(沒(méi)有子元素或超過(guò)一個(gè)子元素)
// 報(bào)錯(cuò)且不渲染任何東西也榄。 這也說(shuō)明Provider下必須只能是一個(gè)
// 子元素
render() {
return Children.only(this.props.children)
}
}
// 如果我們運(yùn)行的環(huán)境是production,則還需要定義
// componentWillReceiveProps原型方法
if (process.env.NODE_ENV !== 'production') {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
const { store } = this
const { store: nextStore } = nextProps
// 如果當(dāng)前對(duì)象與傳遞的對(duì)象不一樣第队,則發(fā)出警告
if (store !== nextStore) {
warnAboutReceivingStore()
}
}
}
Provider.propTypes = {
store: storeShape.isRequired,
children: PropTypes.element.isRequired
}
Provider.childContextTypes = {
store: storeShape.isRequired
}
Provider使用示例
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/count'
import configureStore from './store/configureStore'
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
完整代碼請(qǐng)看這里
參考資料:
https://github.com/ckinmind/ReactCollect/issues/57
https://my.oschina.net/997155658/blog/709155