Lesson 2 Main content: Redux’s design ideas

Foreword (Continued)

React has its own data transfer and event management mechanism, so why bother to introduce a third party? Here are some scenarios to illustrate whether a React reference is necessary:

2. You need Redux

The use of users is complex. Users of different identities have different ways of use (such as ordinary users and administrators). Multiple users can collaborate with each other and interact with the server in large quantities, or use WebSocket View to obtain data from multiple sourcesCopy the code

Of course, Redux is not required for the examples in this chapter, but a simple example is needed for the sake of illustration

To understand Redux’s design philosophy, use a simple example: a simple addition and subtraction, click plus plus one, click minus minus one

I. Work flow of Redux (Express idea)

See graph feeling is a bit disorderly, comb clear, do an explanation to above graph a few nouns above all, what are they used respectively, what function is there

1. Store (Express delivery company)

Store can be regarded as a container, and the whole application can only have one Store, just like the whole application can only designate JINGdong Express company to deliver goods.

import {createStore, combineReducers, applyMiddleware} from 'redux';
const store = createStore(reducer);
Copy the code

3. Action (Express order)

Buyers to buy things to do, of course, to order first. The user can only operate the View (such as clicking on the View), and the user cannot touch State. The change of State corresponds to the change of View, which requires the View to notify the change of State through an Action object. Just like through a Courier order (send an Action), just have the next logistics and a series of operations is not it. Action is a custom object where the Type attribute is mandatory

Cost action = {type:'btnClick', MSG :' info string, not required '}Copy the code

Reducer (Package goods)

After the Store receives an Action, it must present a new State so that the view can change, and the new State is calculated by Reducer. After receiving an order (Action), you need to select goods according to the order and pack them. Reducer is a custom function that accepts Action and the current State as a match and returns a new State

const reducer = (state=defaultState,action) =>{ switch (action.type) { case 'btnClick': Return state + action. MSG +' update '; Case 'other type': return state +' other action.msg '; /* Add more case types to match different actions */ default: return state; }}Copy the code

Next, we sent this set of order processing rules to the Store. If there are orders in the future, we only need to deliver according to these rules

import { createStore } from 'redux'; // store. Dispatch triggers automatic execution of the Reducer const store = createStore(Reducer);Copy the code

If you need to send different actions, add order rules to Reducer. Add case ‘type’ rules to Reducer

summary

React Redux Redux Redux Redux Redux Redux Redux

Redux Redux Redux Redux

If you use Redux’s state management approach to React, you can do it, but it’s a bit of a hassle. Let’s say we want to define the update View at the end

Subscribe (() => console.log(store.getstate ()) render () {// React render () method updates view!! });Copy the code

For ease of use, the authors of Redux have packaged a react-redux library dedicated to React

2, connect ()

React-redux provides the connect method. It’s connecting UI components to container components, so what’s the rule? Need to have:

Input logic: external data (state object) is converted into parameters of UI component. Output logic: the bullet train issued by the user (Action object) is passed out from UI componentCopy the code

Thus, the API for the CONNECT method looks like this:

import { connect } from 'react-redux'

const Comp = connect(
  mapStateToProps,
  mapDispatchToProps
)(UI)
Copy the code

The connect method takes two parameters: mapStateToProps, which is responsible for the input logic, mapping state to the PARAMETER props of the UI component, and mapDispatchToProps, which is responsible for the output logic, mapping user actions to the UI to actions.

(2), mapDispatchToProps ()

MapDispatchToProps is the second parameter to Connect, which is also a function (and can also be an object). MapDispatchToProps, as a function, should return an object where each key-value pair is a mapping that defines how the UI component’s parameters emit actions. Another mapping to the PROPS parameter of the UI component!!

const mapDispatchToProps = (dispatch, ownProps) => { return { increase: (... args) => dispatch(actions.increase(... args)), decrease: (... args) => dispatch(actions.decrease(... args)) } };Copy the code

The mapDispatchToProps function takes two arguments and returns an object with properties corresponding to the PROPS parameter of the UI component. The UI component calls props. Increase to dispatch (Action) and dispatch an Action.

summary

The following figure shows the general working principle of React-Redux. It can be seen that the UI component is only responsible for the UI part. It only uses the props parameter to get data and distribute data to the outside world, but does not do much business logic. The business logic and data rendering are handed over to the container component, the UI component and the container component are linked through the connect () method, and the data is passed internally through mapStateToProps and mapDispatchToProps. The entire application’s data is processed by the Store central processing unit. So the data interaction between different UI components can dump the data to the Store central processing unit, and the Store can then pass the processed data back to each UI component

Three, small example: addition and subtraction

Use a piece of code to reinforce what you’ve learned. Practice intensifies! Ha ha

Main.jsx:

import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; / / class Main extends Component{constructor(){super(); this.pClick =() =>{ console.log('sssssssss'); }; This. State = {num:0, age:666}} render(){const {count, increase, decrease} = this. return( <div> <p className="lesson-2">React lesson-2</p> <p> --------------------------------- </p> <div ClassName ="count"> <div> count: {this.props. Count} times </div> <span className=" BTN "onClick={increase}>+</span> <span className=" BTN" Decrease; onClick={Decrease}>-</span> </div> </div>)}} return { count: state.count } }; /** * const mapDispatchToProps = (dispatch, const mapDispatchToProps = (dispatch, const mapDispatchToProps)  ownProps) => { return { increase: (... args) => dispatch(actions.increase(... args)), decrease: (... args) => dispatch(actions.decrease(... args)) } }; /** * actions */ const actions ={ increase:() => { return {type: 'INCREASE'} }, decrease: () => { return {type: 'DECREASE'} } }; /** * Connect UI component to container component * @param mapStateToProps input logic * @param mapDispatchToProps output logic */ const Comp = connect(mapStateToProps, mapDispatchToProps)(Main); /** * export default Comp;Copy the code

App.js

import React,{Component,PropTypes} from 'react'; import ReactDOM, {render} from 'react-dom'; import {Provider,connect} from 'react-redux'; import {createStore, combineReducers, applyMiddleware} from 'redux'; import Index from './Component/Main.jsx'; import './Style/comm.scss' const store = createStore(reducer); Store. Subscribe (() => {//console.log(store.getState())}); const reducer = (state = {count: 0}, action) => { switch (action.type){ case 'INCREASE': return {count: state.count + 1}; case 'DECREASE': return {count: state.count - 1}; default: return state; } } render( <Provider store={store}> <Index></Index> </Provider>, document.body.appendChild(document.createElement('div')) );Copy the code

You can also clone the project to run debugging

clone [email protected]:ZengTianShengZ/react-lesson.git
cd lesson-2
npm install
npm run hot
Copy the code

conclusion

The above is my learning and experience of Redux. A lot of information comes from the Internet and Daishen’s blog. If you have any questions, you can issue it