React 自制React-Redux
connect负责链接组件,把redux里的数据放到组件属性中
export function connect(){
}
- 负责接受一个组件,把state里的一些数据放进去,返回一个组件
- 数据变化的时候,能够通知组件
分析React-Redux中
App = connect(state=>({num:state}),{add,remove})(App)
高阶组件写法connect
- 实现其中的
mapStateToProps,mapDispatchToProps
参数
export function connect(mapStateToProps,mapDispatchToProps){
return function (WrapComponent){
return class ConnectComponent extends React.Component{
}
}
}
export const connect = (mapStateToProps=state=>state,mapDispatchToProps={})=>(WrapComponent)=>{
return class ConnectComponent extends React.Component{
}
}
Provider把store放到context里,所有的子元素可以直接取到store
class Provider extends React.Component{
}
自制React-Redux
import {bindActionCreators} from './tyrmars-redux.js'
查看自制Redux
import React from 'react'
import PropTyps from 'prop-types'
import {bindActionCreators} from './tyrmars-redux.js'
export const connect = (mapStateToProps=state=>state,mapDispatchToProps={})=>(WrapComponent)=>{
return class ConnectComponent extends React.Component{
static contextType = {
store:PropTypes.object
}
constructor(props){
super(props)
this.state = {
props:{}
}
}
componentDidMount(){
const {store} = this.context
store.subscirbe(()=>this.update())
this.update()
}
update(){
const {store} = this.context
const stateProps = mapStateToProps(store.getState())
const stateDispatch = bindActionCreators(mapDispatchToProps,store.dispatch)
this.setState(
props:{
...this.state.props,
...stateProps,
...stateDispatch,
}
)
}
render(){
return <WrapComponent {...this.state.props}></WrapComponent>
}
}
}
export class Provider extends React.Component{
static childContextTypes = {
store:PropTypes.object
}
getChildContext(){
return {store:this.store}
}
constructor(props,context){
super(props,context)
this.store = props.store
}
render(){
return this.props.children
}
}