react-redux

##1: Understand es7 decorators

Data: www.cnblogs.com/gavin-cn/p/…

Use react-redux

yarn add react-redux
Copy the code

On the use

1. You need a Redux Store

import { createStore, combineReducers } from 'redux'

const countReducer = function (state = 0, action) {
  switch (action.type) {
    case 'add':
      state++
      break
    case 'sub':
      state--
      break
    default:
      return state
  }
  return state
}

const store = createStore(combineReducers({ count: countReducer }))

export default store
Copy the code








2. The writing of components

import React, { Component } from 'react'

import { connect } from 'react-redux'

// Connect is a higher-order component

// Attributes map to props
const mapStateToProps = (state) = > {
  return { count: state.count }
}

// The method maps to props
let mapDispatchToProps = {
  add: () = > {
    return { type: 'add'}},minus: () = > {
    return { type: 'sub'}}},/ / components:

class ReactReduxPage extends Component {
  render() {
    const { count, add, minus, asyAdd } = this.props
    return (
      <div>
        <h1>ReactReduxPage</h1>
        <p>{count}</p>
        <button onClick={add}>add</button>
        <button onClick={minus}>minus</button> 
      </div>)}}// Import via decorator or like this

export default connect(mapStateToProps, mapDispatchToProps)(ReactReduxPage)

Copy the code








3. In addition, you need to provide a store for connet components to fetch

The React-Redux built-in provider provides stores

import React from 'react' import { Provider } from 'react-redux' import store from './store' import RReduxpage from Export default function ReactReduxPage() {return (<div> <Provider store={store}> <RReduxpage /> </Provider> </div> ) }Copy the code