Easy to prepare

  • Use create-react-app to quickly set up the React project
  • NPM install redux react-redux redux-thunk –save redux-thunk
  • Change, new project directory

  • rendering

The Demo start

Write redux content

action

Export const Increment = 'Increment' export const Decrement = 'Decrement' /* Action Creator Action constructor */ export const increment = (counterIndex) => { type:Increment, counterIndex } export const decrement = (counterIndex) => ({ type: Decrement, counterIndex })Copy the code

Actions are essentially JavaScript ordinary objects. You must use a type field of type string inside the action to indicate the action to be performed, but you need to write as many actions as you can, so you need action Creator, the action constructor that returns a JS object, Of course, a function needs to be returned when processing asynchronous data, and middleware needs to be used to rewrite the Dispatch.

reducer

import { Increment, Decrement } from '.. /Action' export default (state,action) => { const {counterIndex} = action switch (action.type) { case Increment: return {... state, [counterIndex]:state[counterIndex]+1} case Decrement: return {... state, [counterIndex]:state[counterIndex]-1} default: return state } }Copy the code

The specific definition of Reducer can be seen in the redux self-statement. Because the demo is too simple, we split and merged reducer. Here we mainly introduce the work flow of Redux in React. Reducer is a pure function and cannot change state. The new state returned by reducer can use Object.assign and es6 Object extenders.

store

import {applyMiddleware, createStore} from 'redux' import thunk from 'redux-thunk' import reducer from '.. /Reducer' const initValue={ 'First':1, 'Second':5, 'Third':6 } const store=createStore(reducer,initValue) export default storeCopy the code

CreateStorestore can accept an initial state where the initialization props of the server isomorphic application can be set. Now that the redux correlation is over, let’s write the UI component.

Writing UI components

If react-Redux is not used to automatically generate container components, there must be a division between container components and presentation components. In my understanding, the presentation component does not have its own state, only accepts props to determine how the UI should be displayed. All logic is performed in the container component. We don’t need to write container components ourselves

Counter

import React, { Component } from 'react'; import {increment, decrement} from '.. /Redux/Action' import {connect} from 'react-redux' import '.. /style/App.css'; const buttonMargin= { margin: "20px" } function Counter({index, Increment, Decrement, value}){ return ( <div> <button style={buttonMargin} onClick={Increment}>+</button> <button style={buttonMargin} onClick={Decrement}>-</button> <span>{index} count :{value}</span> </div> ) } function mapStateToProps(state,ownProps){ return{ value:state[ownProps.index] } } function mapDispatchToProps(dispatch, ownProps){ return{ Increment:() => { dispatch(increment(ownProps.index)) }, Decrement:() => { dispatch(decrement(ownProps.index)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Counter);Copy the code
  • React-redux provides a method, connect(), and a component. The connect method takes two parameters: mapStateToProps and mapDispatchToProps. They define the business logic of the UI components. The former is responsible for the input logic, which maps state to the UI component’s parameters (props), and the latter is responsible for the output logic, which maps user actions on the UI component to actions.
  • MapStateToProps: As a function, mapStateToProps should return an object in which each key-value pair is a mapping. Accept two parameters state, ownProps, state. When state is updated, it automatically recalcates the parameters of the UI component to trigger a re-rendering of the UI component. OwnProps represents the props object of the container component. If the parameters of the container component change, it also triggers a re-rendering of the UI component, such as the count above.
  • MapDispatchToProps is the second parameter to the connect function that maps UI component parameters to the Store. dispatch method. That is, it defines which user actions should be passed to the Store as actions. It can be a function or an object

Panel

import React, { Component } from 'react'
import Counter from './Counter.js'
const style = {
    margin: "20px"
}

class Panel extends Component {
    render() {
        return (
            <div style={style}>
                <Counter index="First" />
                <Counter index="Second"/>
                <Counter index="Third" />
                <hr/>
            </div>
        )
    }
}
Copy the code

export default Panel

So this right here is a list.

Index.js (entry file)

import React from 'react';
import ReactDOM from 'react-dom';
import './style/index.css';
import Panel from './Component/Panel';
import {Provider} from 'react-redux';
import store from './Redux/Store/store.js'
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
       <Provider store={store}>
         <Panel/>
       </Provider>,<pre>
   document.getElementById('root')
  );
registerServiceWorker();
Copy the code

React-redux provides a Provider component that allows container components to get state and avoid cascading. Context is used in vue, which has a bus. This completes a demo of synchronous redux processing data. Let’s talk about asynchrony.

asynchronous

Vuex submitted Mutation (somewhat like Git), which is synchronous and has actions that can synchronize asynchronously, but redux does not, so middleware was introduced to address asynchronous actions. There are several common examples of middleware, which are simply redux-thunk. The Action Creator principle is to return a JS object, async processing here, and return a function, which requires middleware processing. Modify these two:

Action:

export const Increment = 'increment' export const Decrement = 'decrement' export const increment = (counterIndex) => { return dispatch => { let asyncAct = { type:Increment, CounterIndex} setTimeout(()=>{// Send action Dispatch (asyncAct) after two seconds; }, 2000) } } export const decrement = (counterIndex) => ({ type: Decrement, counterIndex })Copy the code

store:

import {applyMiddleware, createStore} from 'redux' import thunk from 'redux-thunk' import reducer from '.. /Reducer' const initValue={ 'First':1, 'Second':5, 'Third' : 6} const store = createStore (reducer, initValue applyMiddleware (thunk)) / / the use of middleware of writing applyMiddleware, if more than one, Note the order of middleware export Default StoreCopy the code

Simple delay 2s counting is done.