美文网首页
React-Redux的理解与实现

React-Redux的理解与实现

作者: 吴晗君 | 来源:发表于2019-07-06 18:43 被阅读0次

    React-Redux

    这个库出现的意义就是将redux和react进行连接。能够让各子组件能够使用到存储在redux store中的数据。也进行了很多性能优化的地方。
    connect.js

    import React from 'react'
    import {bindActionCreators} from '../redux'
    import ReactReduxContext from './ReactReduxContext'
    
    export default function connect (mapStateToProps, mapDispatchToProps) {
      return function (WrappedComponent) {
        return class extends React.Component{
          static contextType = ReactReduxContext
    
          constructor (props, context) {
            super(props)
            this.state = mapStateToProps(context.store.getState())
          }
          componentDidMount () {
            this.unsubscribe = this.context.store.subscribe(() => {
              this.setState(mapStateToProps(this.context.store.getState()))
            })
          }
          componentWillUnmount () {
            this.unsubscribe()
          }
          render () {
            let actions = bindActionCreators(mapDispatchToProps, this.context.store.dispatch)
            return <WrappedComponent {...actions} {...this.state} />
          }
        }
      }
    }
    

    provider.js

    import React, {Component} from 'react'
    import ReactReduxContext from './ReactReduxContext'
    
    export default class Provider extends Component{
      render () {
        return <ReactReduxContext.Provider value={{store: this.props.store}}>
          {this.props.children}
        </ReactReduxContext.Provider>
      }
    }
    
    

    ReactReduxContext.js

    import React from 'react'
    
    export default React.createContext(null)
    

    相关文章

      网友评论

          本文标题:React-Redux的理解与实现

          本文链接:https://www.haomeiwen.com/subject/rldmhctx.html