關於react-redux中Provider、connect的解析


Provider

是什么

react-redux 提供的一個 React 組件

作用

把 store 提供給其子組件

  1. //使用 redux 的 createStore 方法創建的一個 store
  2. const store = createStore(todoApp,{})
  3. // store 作為一個 prop 傳給 Provider 組件
  4. render(
  5. <Provider store={store}>
  6. <App/>
  7. </Provider>, document.getElementById('app'))

connect

  1. connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

作用

把“指定的state & 指定的action”和 React組件 連接起來 ==> 容器組件

參數說明

mapStateToProps

這是一個function,返回一個object;

(state, [ownProps]) => ({ }) // 通常省略第二個參數

作用 把指定的state作為props注入到 UI組件 中

  1. const mapStateToProps = state => {
  2. return {
  3. title: state.title
  4. list: state.list
  5. };
  6. }

當然,不必將 state 中的數據原封不動地傳入組件,可以根據 state 中的數據,動態地輸出組件需要的(最小)屬性。

  1. const mapStateToProps = (state) => {
  2. return {
  3. greaterThanFive: state.count > 5 // 假如只需要知道count大不大於5就成
  4. }
  5. }

函數的第二個參數 ownProps,是 React的UI組件自己的 props。有的時候,ownProps 也會對其產生影響。
比如,當你在 store 中維護了一個用戶列表,而你的組件只關心一個用戶。

  1. const mapStateToProps = (state, ownProps) => {
  2. // state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}
  3. return {
  4. user: _.find(state.userList, {id: ownProps.userId})
  5. }
  6. }
  7. class MyComp extends Component {
  8. static PropTypes = {
  9. userId: PropTypes.string.isRequired,
  10. user: PropTypes.object
  11. };
  12. render(){
  13. return <div>用戶名:{this.props.user.name}</div>
  14. }
  15. }
  16. const Comp = connect(mapStateToProps)(MyComp);

mapDispatchToProps

這可以是一個function,還可以是object,

作用 把指定的action作為props注入到UI組件中

  1. // 方法
  2. const mapDispatchToProps = dispatch => {
  3. return {
  4. destroyTodo : () => dispatch({
  5. type : 'DESTROY_TODO'
  6. })
  7. }
  8. }
  9. // 對象

mergeProps

是一個函數,用來篩選哪些參數傳遞給組件。這個函數接受3個參數

  1. const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({
  2. ...ownProps,
  3. ...stateProps,
  4. ...dispatchProps
  5. })

stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是當前組件自己的屬性。
這個函數默認把這三個返回值拼裝到一起傳遞給組件,可修改。

options

一個對象,有兩個布爾,一個是pure,一個是withRef。

  • pure為false,只要connect接受到屬性,不管是否有變化,必然刷新connect組件。
  • withRef為true時,在裝飾傳入的 React 組件時,Connect 會保存一個對該組件的 refs 引用,可以通過 getWrappedInstance 方法來獲得該 refs,並最終獲得原始的 DOM 節點。

使用

  1. const newApp = connect(store)(UI)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM