zoukankan      html  css  js  c++  java
  • redux和react-redux在react中的使用

     

    App.js:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types'
    import { createStore } from 'redux'
    import { Provider } from 'react-redux'
    import Header from './Header'
    
    const themeReducer = (state, action) => {
      if (!state) return {
        themeColor: 'red'
      }
      switch (action.type) {
        case 'CHANGE_COLOR':
          return { ...state, themeColor: action.themeColor }
        default:
          return state
      }
    }
    
    const store = createStore(themeReducer)
    
    class App extends Component {
      render() {
        return (
          <Provider store={store}>
            <Header />
          </Provider>
        );
      }
    }
    
    export default App;
    

    Header.js:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types'
    import { connect } from 'react-redux'
    import ThemeSwitch from './ThemeSwitch'
    
    class Header extends Component {
      static propTypes = {
        themeColor: PropTypes.string
      }
    
      render () {
        return (
          <div>
            <h1 style={{ color: this.props.themeColor }}>xutongbao</h1>
            <ThemeSwitch/>
          </div>
        )
      }
    }
    
    const mapStateToProps = (state) => {
      return {
        themeColor: state.themeColor
      }
    }
    Header = connect(mapStateToProps, null)(Header)
    
    export default Header
    

    ThemeSwitch.js:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types'
    import { connect } from 'react-redux'
    
    class ThemeSwitch extends Component {
      static contextTypes = {
        store: PropTypes.object
      }
    
      handleSwitchColor (color) {
        if (this.props.onSwitchColor) {
          this.props.onSwitchColor(color)
        }
      }
    
      render () {
        return (
          <div>
            <button onClick={this.handleSwitchColor.bind(this, 'red')}>Red</button>
            <button onClick={this.handleSwitchColor.bind(this, 'blue')}>Blue</button>
          </div>
        )
      }
    }
    
    const mapDispatchToProps = (dispatch) => {
      return {
        onSwitchColor: (color) => {
          dispatch({ type: 'CHANGE_COLOR', themeColor: color })
        }
      }
    }
    ThemeSwitch = connect(null, mapDispatchToProps)(ThemeSwitch)
    
    export default ThemeSwitch
    
  • 相关阅读:
    投简历——个人记录
    光电经纬仪——查资料
    Spring Boot(十三):spring boot小技巧
    Spring Boot(十二):spring boot如何测试打包部署
    Python3 hasattr()、getattr()、setattr()函数简介
    Python3 格式化字符串
    Python3 join函数和os.path.join用法
    Python3 根据m3u8下载视频,批量下载ts文件并且合并
    it commit提示Your branch is up-to-date with 'origin/master'.
    git下,输入git log 进入log 怎么退出
  • 原文地址:https://www.cnblogs.com/xutongbao/p/9924770.html
Copyright © 2011-2022 走看看