美文网首页
react-redux基本用法

react-redux基本用法

作者: louhangfei | 来源:发表于2019-03-04 22:03 被阅读0次
    import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    import ReactDOM from 'react-dom'
    import { createStore } from 'redux'
    import { Provider, connect } from 'react-redux'
    
    // React component
    class Counter extends Component {
      render() {
        const { value, onIncreaseClick } = this.props
        return (
          <div>
            <span>{value}</span>
            <button onClick={onIncreaseClick}>Increase</button>
          </div>
        )
      }
    }
    
    Counter.propTypes = {
      value: PropTypes.number.isRequired,
      onIncreaseClick: PropTypes.func.isRequired
    }
    
    // Action
    const increaseAction = { type: 'increase' }
    
    // Reducer
    function counter(state = { count: 0 }, action) {
      const count = state.count
      switch (action.type) {
        case 'increase':
          return { count: count + 1 }
        default:
          return state
      }
    }
    
    // Store
    const store = createStore(counter)
    
    // Map Redux state to component props
    function mapStateToProps(state) {
      return {
        value: state.count
      }
    }
    
    // Map Redux actions to component props
    function mapDispatchToProps(dispatch) {
      return {
        onIncreaseClick: () => dispatch(increaseAction)
      }
    }
    
    // Connected Component
    const App = connect(
      mapStateToProps,
      mapDispatchToProps
    )(Counter)
    
    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    )
    

    相关文章

      网友评论

          本文标题:react-redux基本用法

          本文链接:https://www.haomeiwen.com/subject/iowwuqtx.html