This. State = this. State = this. State = this. State = this.

React data stream: 1.As can be seen, usually the senior cadres such as the head of the group discuss the countermeasures (this. State is set).

2. Pass the commands down the props (this.props)

3. If there is a new enemy situation (want to update page content)

4. You have to report layer by layer (pass data up layer by layer by callback), and the process must be passed up layer by layer, not beyond the hierarchy, as explained below

5. After the leader makes a decision, the command will be issued for execution (setState is used to modify data and re-render).

 

This process can’t skip steps, such as a company commander found enemy you cannot report head directly, and must report to a battalion commander, a battalion commander to report to the colonel, hierarchy is not particularly deep, here you come again a platoon leader, monitor what of, according to this model, such as colonel know the situation of the enemy, the enemy has hit the door, or a company commander to find three company commander to drink wine, The news had to be passed first to the battalion commander, then to the colonel, then to the second battalion commander, then to the third company commander.

 

Redux was born

So the hierarchy is not deep, the set price between public data, there is nothing with the React setState can actually itself, but a deep nested, or there are some public data component is more troublesome, so there will be a story (before you actually have a flux), back to this case, They created a communications team (Redux) outside the regiment:

 

Distinguish between two states

Before I talk about Redux, I would like to mention that I encountered a small problem when I learned Redux, which is that state in Redux is completely different from state in React. State in React is the internal state information of a component, while state in Redux is Redux’s own data. Then React uses the data from Redux, but Redux can also be used in other frameworks, it doesn’t have to be used with React.

A simple diagram would look something like this:

This is just a very simple schematic diagram, which is not the case in actual use. This diagram is to make you understand that the data in React and Redux are independent and have nothing to do with each other

 

Redux

Now let’s move away from React and focus on Redux.

In fact, there are many tutorials on Redux on the Internet. Here is a brief introduction:

store

Store: First create an object called store. This object has various methods for the outside world to retrieve the Redux’s data (store.getState) or to modify the Redux’s data (store.dispatch).

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

 

action

{type: ‘request reinforcements’}, gun:”100″}, type:’ request reinforcements’}

reducer

Reducer: Let’s say the commander of a company asks for 100 guns, so the reducer will send them to you right away.

const defaultState = 0; Const Reducer = (state = defaultState, action) => {switch (action.type) {case 'request to reduce ': return state + action.gun; default: return state; }};Copy the code

 

 

Action and Reducer can also be thought of as the relationship between product managers and programmers.

Product manager: “I want a button with rounded corners.”

Programmer: “Yeah, done.”

Product manager: “Change color, red.”

Programmer: “OK, it’s done”

The product manager doesn’t worry about how to do it, he just says what he wants to do (type), and then adds the requirements (various other data), and the programmer implements the reducer (reduce state). Instead of returning the original state, we return a new state object, since the Reducer function is a pure function with no side effects.

How do I trigger this action? It’s like my company commander has found the enemy. How do I report it to the communications team and let the communications team handle it?

It’s the same store.dispatch as mentioned above, but with one additional argument: action

Store.dispatch ({type: 'call for backup', gun:"100"})Copy the code

 

In this way, we can trigger the action, execute the Reducer, and get a new state.

The story and the React

At this point, Redux is done by itself, so Redux’s own data is not useful, it needs to use the data to React, so let’s talk about how to use the data to React.

We’ve created an object store, and we’re going to pass this store object to React as props, so React will work.

There can only be one store, so you can only create it once, which means you have to create a store object at the top and pass it through the layers so that all components can get the store object and call its methods.

Get the data in Redux

For example, if I want to display Redux’s data in the render function, I can get its data first:

store.getState()
Copy the code

Then render this data to the component as props.

 

Update the data in Redux

If you want to modify its data, call it in JSX

Store.dispatch ({type: 'call for backup', gun:"100"})Copy the code

 

In response to changes in the Redux

So here’s the problem again: the data in Redux does change after you call Store. dispatch, but nothing changes when you React. If you change the state in React, it’s useless. If you change the state in React, you have to call the setState in React.

So, in order to make Redux rerender as soon as the Redux data changes, Redux itself provides a method called

store.subscribe(render)
Copy the code

This function listens for changes in the state in Redux. If the state in Redux changes, the render function is called and the page is rerendered.

 

This procedure is called manually, but it’s a bit of a hassle because to make sure that all the child components can use the data in the Store, all the components would need to pass in the store as props.

Or that before the example, you a company commander found the enemy situation, is not layer upon layer to report, can directly report to the communication class, communication class into a new order, but the problem is, you from the bottom to the report is simple, but from the top to the next to issue orders is still layer upon layer of transmission.

For example, if a company commander discovers the enemy situation and reports it, the communications squad makes a decision to let the third company commander lead people to fight. The communications squad still has to go through the road of colonel — battalion commander — company commander to issue orders one by one. Can the communications squad directly notify the third company commander

 

React-redux

This is something you need to install extra using NPM.

Using this method, we don’t need to issue commands down the hierarchy

There are two key concepts in React-Redux: Provider and connect methods.

Generally, we wrap the top-level components in Provider components, so that all components are under the react-Redux control, but the store must be put in the Provider component as a parameter

<Provider store = {store}> <Provider>Copy the code

The purpose of this component is to make the data in Redux accessible to all components.

This is a little bit easier, so we’re going to focus on the connect method.

The connect method:

connect(mapStateToProps, mapDispatchToProps)(MyComponent)
Copy the code

 

The connect method actually has four parameters, the first two of which are mainly discussed here.

mapStateToProps

= props = props = props = props = props = props

Which data from the Redux do you want to use with React?

For example, here the erlian component wants to render the number of its guns. You can take gunOfErlian from Redux and use it directly in the erlian component

const mapStateToProps = (state) => {
  return {
    gun: state.gunOfErlian
  }
}
Copy the code

Then you can use this.props. Gun when rendering

class Erlian extends Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
            <div>this.props.gun</div>
        )
    }
}
Erlian = connect()(Erlian);
export default Erlian;
Copy the code

 

So we can render it by changing state in Redux to props in React.

 

mapDispatchToProps

It makes sense to use this function, which turns dispatches into props for you to use

And that brings us to the most important point here.

Const mapDispatchToProps => {return {onClick: () => {dispatch({type: 'call for props ', gun: 100}); }}; }Copy the code

Change the Erlian component above

class Erlian extends Component { constructor(props){ super(props); } render(){return(<div>this.props. Gun </div> <button onClick = {this.props. OnClick </button>)}} Erlian = connect()(Erlian); export default Erlian;Copy the code

When I click the “call for reinforcements” button, the number of Erlian component guns will be automatically updated, instead of needing us to manually subscribe to the Render function with store.subscribe to update the page.

This way, we don’t need to pass store objects in layers.

This is a convenient way to use and modify the data in Redux anywhere, but the best practice recommended by Redux is to use Connect in as few places as possible, and to put all the logic and data related processing in the container components. The rest of the components are passed down the props generated by the container component and rendered (the dummy component), but I won’t go into that here.