- Provider 为后代组件提供store
//connect 链接store与组件 其实这里返回的是一个新的组件//谨慎使用ownProps,若果ownProps 发生变化,mapStateToProps会被重新执行,state也会重新计算export default connect( // state => ({count: state}) (state,ownProps) => { console.log(ownProps); return { count:state } }, // mapDispatch objec / function // // { // add: ()=>{type:"ADD"} // } // (dispatch)=>{ // let res = {add:()=>dispatch({type:"ADD"})} // res = bindActionCreators(res,dispatch) // return { // dispatch, // ...res // } // } (stateProps, dispatchProps,ownProps)=>{ return {...stateProps,...dispatchProps,...ownProps} })( class ReactReduxPage extends Component { render(){ console.log("props") const {count,dispatch} = this.props return ( <div> <h3>ReactReducx</h3> </div> ) } })//kReactReduximport React, { Component } from 'react'const ValueContext = React.createContext();export const connect = (mapStateToProps =state=>state,mapDispatchToProps)=>WrappedComponent=>{ return class extends Component { //此时组件的所有生命周期都能获得this.context static contextType = ValueContext constructor(props){ super(props); this.state = { props:{} } } componentDidmount(){ const {subscribe} = this.context this.update() subscribe(()=>{ this.update() }) } update = ()=>{ const {getState,dispatch,subscribe} = this.context let stateProps = mapStateToProps(getState()) let dispatchProps = dispatch; if(typeof mapDispatchToProps === object){ dispatchProps = bindActionCreators(mapDispatchToProps,dispatch) }else if(typeof mapDispatchToProps === 'function'){ dispatchProps = mapDispatchToProps(dispatch,this.props) }else{ dispatchProps = {dispatch} } this.setState({ props:{ ...stateProps, ...dispatchProps } }) } render(){ return <WrappedComponent {...this.state.props}/> } }}export class Provider extends Component { render() { <ValueContext.Provider value={this.props.store}> {this.props.children}; </ValueContext.Provider> }}function bindActionCreators(creator,dispatch){ return (...args)=>dispatch(creator(...args))}// {// add:()=>{{type:"ADD"}}// }export function bindActionCreators(creators,dispatch){ const obj = {}; for(const key in creators){ obj[key] = bindActionCreators(creators[key]) } return obj}