1. Provider 为后代组件提供store
    1. //connect 链接store与组件 其实这里返回的是一个新的组件
    2. //谨慎使用ownProps,若果ownProps 发生变化,mapStateToProps会被重新执行,state也会重新计算
    3. export default connect(
    4. // state => ({count: state})
    5. (state,ownProps) => {
    6. console.log(ownProps);
    7. return {
    8. count:state
    9. }
    10. },
    11. // mapDispatch objec / function
    12. //
    13. // {
    14. // add: ()=>{type:"ADD"}
    15. // }
    16. // (dispatch)=>{
    17. // let res = {add:()=>dispatch({type:"ADD"})}
    18. // res = bindActionCreators(res,dispatch)
    19. // return {
    20. // dispatch,
    21. // ...res
    22. // }
    23. // }
    24. (stateProps, dispatchProps,ownProps)=>{
    25. return {...stateProps,...dispatchProps,...ownProps}
    26. }
    27. )(
    28. class ReactReduxPage extends Component {
    29. render(){
    30. console.log("props")
    31. const {count,dispatch} = this.props
    32. return (
    33. <div>
    34. <h3>ReactReducx</h3>
    35. </div>
    36. )
    37. }
    38. }
    39. )
    40. //kReactRedux
    41. import React, { Component } from 'react'
    42. const ValueContext = React.createContext();
    43. export const connect = (mapStateToProps =state=>state,mapDispatchToProps)=>WrappedComponent=>{
    44. return class extends Component {
    45. //此时组件的所有生命周期都能获得this.context
    46. static contextType = ValueContext
    47. constructor(props){
    48. super(props);
    49. this.state = {
    50. props:{}
    51. }
    52. }
    53. componentDidmount(){
    54. const {subscribe} = this.context
    55. this.update()
    56. subscribe(()=>{
    57. this.update()
    58. })
    59. }
    60. update = ()=>{
    61. const {getState,dispatch,subscribe} = this.context
    62. let stateProps = mapStateToProps(getState())
    63. let dispatchProps = dispatch;
    64. if(typeof mapDispatchToProps === object){
    65. dispatchProps = bindActionCreators(mapDispatchToProps,dispatch)
    66. }else if(typeof mapDispatchToProps === 'function'){
    67. dispatchProps = mapDispatchToProps(dispatch,this.props)
    68. }else{
    69. dispatchProps = {dispatch}
    70. }
    71. this.setState({
    72. props:{
    73. ...stateProps,
    74. ...dispatchProps
    75. }
    76. })
    77. }
    78. render(){
    79. return <WrappedComponent {...this.state.props}/>
    80. }
    81. }
    82. }
    83. export class Provider extends Component {
    84. render() {
    85. <ValueContext.Provider value={this.props.store}>
    86. {this.props.children};
    87. </ValueContext.Provider>
    88. }
    89. }
    90. function bindActionCreators(creator,dispatch){
    91. return (...args)=>dispatch(creator(...args))
    92. }
    93. // {
    94. // add:()=>{{type:"ADD"}}
    95. // }
    96. export function bindActionCreators(creators,dispatch){
    97. const obj = {};
    98. for(const key in creators){
    99. obj[key] = bindActionCreators(creators[key])
    100. }
    101. return obj
    102. }