实现 React-redux(三) Provider

react-redux.js:

  1. import React, { Component } from 'react'
  2. import PropTypes from 'prop-types'
  3. export const connect = (mapStateToProps, mapDispatchToProps) => (WrappedComponent) => {
  4. class Connect extends Component {
  5. static contextTypes = {
  6. store: PropTypes.object
  7. }
  8. constructor () {
  9. super()
  10. this.state = {
  11. allProps: {}
  12. }
  13. }
  14. componentWillMount () {
  15. const { store } = this.context
  16. this._updateProps()
  17. store.subscribe(() => this._updateProps())
  18. }
  19. _updateProps () {
  20. const { store } = this.context
  21. let stateProps = mapStateToProps
  22. ? mapStateToProps(store.getState(), this.props)
  23. : {} // 防止 mapStateToProps 没有传入
  24. let dispatchProps = mapDispatchToProps
  25. ? mapDispatchToProps(store.dispatch, this.props)
  26. : {} // 防止 mapDispatchToProps 没有传入
  27. this.setState({
  28. allProps: {
  29. ...stateProps,
  30. ...dispatchProps,
  31. ...this.props
  32. }
  33. })
  34. }
  35. render () {
  36. return <WrappedComponent {...this.state.allProps} />
  37. }
  38. }
  39. return Connect
  40. }
  41. export class Provider extends Component {
  42. static propTypes = {
  43. store: PropTypes.object,
  44. children: PropTypes.any
  45. }
  46. static childContextTypes = {
  47. store: PropTypes.object
  48. }
  49. getChildContext () {
  50. return {
  51. store: this.props.store
  52. }
  53. }
  54. render () {
  55. return (
  56. <div>{this.props.children}</div>
  57. )
  58. }
  59. }

App.js:

  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types'
  3. import Header from './Header'
  4. import { Provider } from './react-redux'
  5. function createStore (reducer) {
  6. let state = null
  7. const listeners = []
  8. const subscribe = (listener) => listeners.push(listener)
  9. const getState = () => state
  10. const dispatch = (action) => {
  11. state = reducer(state, action)
  12. listeners.forEach((listener) => listener())
  13. }
  14. dispatch({}) // 初始化 state
  15. return { getState, dispatch, subscribe }
  16. }
  17. const themeReducer = (state, action) => {
  18. if (!state) return {
  19. themeColor: 'red'
  20. }
  21. switch (action.type) {
  22. case 'CHANGE_COLOR':
  23. return { ...state, themeColor: action.themeColor }
  24. default:
  25. return state
  26. }
  27. }
  28. const store = createStore(themeReducer)
  29. class App extends Component {
  30. render() {
  31. return (
  32. <Provider store={store}>
  33. <Header />
  34. </Provider>
  35. );
  36. }
  37. }
  38. export default App;

 

 

 

 

posted @ 2024-03-18 09:39  mounter爱学习  阅读(57)  评论(0编辑  收藏  举报