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)
网友评论