React Redux and Panhu

This is a detailed React Redux literacy text.

React Redux already familiar to students can see directly "React Redux Panhu with his mother" .

What is

React Redux is Redux 's React version, Redux itself independently of the other frameworks exist, it can be combined with other views framework uses, such as React here.

Doing it

Press personal understanding, Redux state management framework is applied in the form of an event stream for transmission events, process, operational status and state feedback.

So still too abstract, give a simple example. For example, there is a component A, it should change its own text inside a div, assume that the text of this.props.contentthe decision, then it can send an event, this event through a series of processing, will eventually change this.props.content.

Turtle, which is too show it, a change of the text had to be so complicated? Yes, if this is the case go with React Redux, it is simply superfluous, nothing good. Here is an article by You Might Not Need Redux , you can consider the application I have written, whether you really need React Redux.

Back to the above example, if A component B component gonna change a sibling of the text inside it? According to our previous practice, we will put on a layer of a Parent AB assembly components, will modify the text of the method that the B component A component assembly after changing the state Parent A component calls, and then change the text B component.

So our code look something like this:

//Parent 组件
render() {
    return (
      <div>
        <A onClick={(newContent) => this.setState({content: newContent})}/>
        <B content={this.state.content}/>
      </div>
    )
}

//A 组件
render() {
    return (
      <div onClick={() => this.props.onClick('This is new content for B')}>Change B's content</div>
    )
}

//B 组件
render() {
    return (
      <div>{this.props.content}</div>
    )
}

A bit strenuous it ... but we finally realized the function ~

what? Added a sibling of C components, but also to change the component A text inside ...

what? There is a depth of the assembly 100, it is changed to the text component B ...

I Panhu out a cigarette, came back to see these two functions to achieve, if not all of you die hammer.

In order to achieve these two functions, the callback function everywhere, especially in the second function, you have to pass a callback function layer 100 down ...

Almost this time, you should consider React Redux up.

Like the second function, just from the deep component sends out an event, this event will change the final text B component.

Wow, that sounds good.

Long-sawed

We talk so much, it's time to see the true capacity React Redux.

RR architecture

Wherein Action, Dispatch and Reducer are React something of Redux, View is representative of our view layer React.

To clarify a few concepts: Store, Action and Reducer (Dispatch is a method of Store)

  • Store the entire application React Redux general state of the container, an object
  • Action is also an object, shows that event, the need for typefield
  • Reducer is a function that will return different data determined depending Action

View from the above layer may be seen in FIG updated in two ways:

  1. View layer emits Action, after arriving Reducer Dispatch, returns the new things to update View Reducer after treatment
  2. Other Action layer emitting in the same way to update the View

Either way above, is rule-way data flow, namely: transmitting Action -> Reducer return data based Action -> Store is updated -> View is updated .

Let's talk about the demo

Talk, hard work and prosperous. Or while writing introduced as well.

Here achieve a small demo, on a button and a number, click the button number plus 1, that counter.

Let me talk a little, React Redux will set up a container divided into components and UI components , the former will deal logic, which is responsible only for display and interaction, not internal processing logic state is completely controlled by the outside.

"I also responsible for some components responsible for displaying and processing logic, you are afraid not embarrass me Gian"

Yes, in many cases like this, it is common practice in the outside layer of the package, the release logic and UI, the write logic outer layer, inner layer of pure writing UI.

So for this component counter, we need multi-layer package, using react-reduxthe connectfunction. This function is connected with the name suggests, UI components are connected, comprising generating a new logic components.

connect Is a higher-order functions, can pass two functions:

import { connect } from 'react-redux';
import Counter from './Counter';

function mapStateToProps(state) {
    return {
        count: state.count
    }
}

function mapDispatchToProps(dispatch) {
    return {
        onAdd: () => dispatch({type: 'ADD_COUNT'})
    }
}

const newComponent = connect(mapStateToProps, mapDispatchToProps)(Counter);

connect Functions can be passed two functions:

mapStateToProps

This function receives state parameters (will be mentioned later, from the state where the reducer over), the definition of the rule to the state transition from the UI component props. This function returns the object props, we take the example of the state countfield to generate a new return props.

This function may also receive ownProps parameter representative of props declared directly in the UI components:

function mapStateToProps(state, ownProps) {
    console.log(ownProps);	//{content: 'hello', color='white'}
  	return {};
}
 
//比如我们是这么使用 Counter 组件的
<Counter content='hello', color='white' />

mapDispatchToProps

This function receives the dispatch parameter (actually the dispatch method Store), define a series of events transmission method, and the object returns props. For example, the above definitions we send ADD_COUNTmethod for the event onAdd, which {type: 'ADD_COUNT'}is a simple Action a.

And so on, Gian has something to say.

You said mapStateToPropsreturn props UI components, mapDispatchToPropsalso returns props UI components, while also define their own UI components props, props that what his mother last UI component is ah?

The answer is that these three props together in one . That is, according to the above example, the internal component can be called Counter to these:

this.props.content;
this.props.color;
this.props.count;
this.props.onAdd();

export default class Counter extends React.Component {
    
  render() {
      return (
        <div>
          <p>{this.props.count}</p>
          <button onClick={this.props.onAdd}>Add</button>
        </div>
      )
  }
}

Well, with connectput the container assembly is configured outer Well, we just put that contains a connectnamed file function is index.jsx.

Reducer

We just wrote the Counter, in fact, not be used, because after we send out event, did not handle the event.

Reducer is used, in fact, is a function of processing Action, such as we deal with the above-mentioned ADD_COUNTevents:

//counter-reducer.js
export default function reducer(state={count: 0}, action) {
    switch(action.type) {
      case 'ADD_COUNT':
        return {
            count: state.count + 1
        };
      default:
        return state;
    }
}

Like here, if we judge the event type is ADD_COUNTwhen the state inside the countfield and property values +1 returns a new state object that will be passed mapStateToPropsin.

Reducer function inside there are 2 points worth noting:

  • The first parameter indicates the current state of the state, for example, when the figure was 1 Click the Add button, then the state is in the Reducer {count: 1}, then returned {count: 2}, then the next is coming {count: 2}up. state initialization value can be passed, such as where we initially zero
  • Any event that all of Reducer can receive , case Reducer if there is no match, the representative does not respond to this event, to return to the current state, that is, default branch return state.

Store

It was also curious that exists in this state in the end it is where? Currently we discussed the Reducer and mapStateToPropsfunctions, they are accepting state, itself does not hold state.

。。。

In fact, state exist in the Store. Will be mentioned later, the case where a plurality of Reducer, corresponding to a Reducer in a state Store.

Well, Store is how to effect our DOM tree?

React Redux by this Store Provider component to bind to a global state of the container DOM tree, as general Provider topmost application component React Redux (Provider was not real in the DOM tree):

import { createStore, Provider } from 'react-redux';
import React from 'react';
import reducer from './counter-reducer.js';
import Counter from './components/Counter';

const store = createStore(reducer);

ReactDOM.render(
  <Provider store={store}>
    <Counter/>
  </Provider>, document.getElementById('root'));

We can see from react-reduxthe introduction of this library createStore Providerand use createStoreto create an incoming Store above Reducer, then spread Store Provider component, which acts on the entire DOM structure.

At this point the project structure (of course, what other webpack profile, not listed):

Project
    - components
        - Counter
        - index.jsx
        - Counter.jsx
    - index.jsx

So far, this has been able to counter the normal functioning.

We also understand a little React Redux works and the way, and then some summary:

  • 事件流:dispatch(Action) -> Reducer -> new state (Store) -> new props -> update component
  • Into container assembly and UI components, conventional components may need to be treated connect
  • Action deal with the situation Reducer return the new state, we need to consider Action mismatch
  • Creating Store, Reducer use createStore function as a parameter
  • Provider used as the top layer assembly incorporated global Store

Gian-ray

———

Technical problems, welcome to the discussion.

Personal blog: mindjet.github.io

In recent Github on maintenance projects:

  • LiteWeather [with a Kotlin write, MD-based style of lightweight weather App] , to use Kotlin be interested in the actual development of the students can see, the project will be used to Kotlin commission mechanism, the expansion mechanism and all kinds of new stuff .
  • Reask [React & Flask with full stack development projects, front-end-Redux REACT] .
  • LiteReader [MD based on a very light reading App, provide know almost daily, IMDb and other resources] , the project mainly use the MVVM design pattern, follow the Material Design interface specifications, providing lightweight reading experience.
  • LiveMVVM [prepared by the Android the MVVM frame Kotlin, Architecture-based Android] , lightweight MVVM + Databinding development framework.

Welcome star / fork / follow mention the issue and PR.

Guess you like

Origin www.cnblogs.com/homehtml/p/11794235.html