current position:Home>Data flow of react Advanced Series

Data flow of react Advanced Series

2021-08-27 05:45:06 campcc

I've been reading practice recently 《 In simple terms, it's done React》, The author's writing style and style are very interesting , There is no shortage of dry goods , After Rereading several times, I still get a full harvest , I sorted out my notes and shared them with you . This series probably has 15 piece , If you think it's helpful, you can give me star, If you find any problems, please correct them in the comment area .

Data flow

React The core feature of the project is Data-driven view , This feature is expressed by a very famous functional expression in the industry :

UI = render(data)
UI = f(data)
 Copy code 

React Your view will change as the data changes , What we call component communication is actually the data connection established between components , Behind this is a set of interlocking React Data flow solutions .

be based on props One way data flow of

be based on props The ginseng , Can achieve a simple father and son , Child parent and sibling components communicate , One way data flow , It refers to the of the current component state With props When flowing in the form of , It can only flow to components lower than itself in the component tree .React One way data flow scenarios in include ,

  • be based on props The father son correspondence : Parent component state As a subcomponent props
  • be based on props Child parent communication : The parent component passes a function that binds its own context
  • be based on props Brother component communication : The parent component does not exist , Convert to child parent + Parent child communication

Above is props There are three scenarios in which parameter transfer is more suitable for processing , If the communication requirements are complex , be based on props One way data flow may not be suitable for , We need to consider other more flexible options , For example, communication problems “ Jack of all trades ”: Release - A subscription model .

utilize “ Release - subscribe ” Pattern driven data flow

Release - The advantage of the subscription model is , As long as the components are in the same context , The location of the listening event and the location of the triggering event are not limited , Therefore, in principle, we can realize the communication of any component based on publish subscribe mode , Here's a simple one EventEmitter,

class EventEmitter {
  constructor() {
    this.eventMap = {};

  on(type, handler) {
    if (!(handler instanceof Function)) {
      throw new Error('event handler expect to be a function');
    if (!this.eventMap[type]) {
      this.eventMap[type] = [];

  emit(type, params) {
    if (this.eventMap[type]) {
      this.eventMap[type].forEach((handler, index) => {

  off(type, handler) {
    if (this.eventMap[type]) {
      this.eventMap[type].splice(this.eventMap[type].indexOf(handler) >>> 0, 1);
 Copy code 

In addition to the two ways described above , We can also use React Global communication mode provided by native Context API.

Use Context API Maintain global status

Context API yes React An official way of global communication of component tree .

Context Based on producer - Consumer model , Corresponding to React There is Three key elements :React.createContext、Provider、Consumer. By calling React.createContext, You can create a set of Provider.Provider As the provider of data , Data can be distributed to any level of the component tree Consumer, and Cosumer Not only can you read Provider Data issued , You can also read these data and subsequent updates ,

const AppContext = React.createContext();
const [Provider, Consumer] = AppContext;

<Provider value={ content: this.state.content }> <Content /> </Provider>

<Consumer> {value => <div>{value.content}</div>} </Consumer>
 Copy code 

Here is Context A simple illustration of the workflow ,


But in V16.3 Before , Due to various limitations ,Context Not be React The government advocates the use of , old Context What are the limitations ?

  • The code is not elegant enough : Producers need to define childContextTypes and getChildContext, Consumers need to define contextTypes Can pass this.context Access the data provided by the producer , Property settings and API Writing is too cumbersome , It's hard to tell who is Provider, Who is the Consumer

  • Data may not be synchronized in time : The question is React There was an official introduction , If the component provides a Context There is a change , And the middle parent component shouldComponentUpdate Back to false, Then descendant components that use this value will not be updated , This goes against the pattern of “Cosumer Not only can you read Provider Data issued , You can also read these data and subsequent updates ” The definition of , As a result, data may not be synchronized in time between producers and consumers .

V16.3 Post new Context API Improved this , Even if the shouldComponentUpdate return false, It can still “ through ” Components continue to propagate to descendant components , Coupled with more elegant semantic declarative writing ,Context Become a practical React Component communication solution .

I understand Context API The past and this life , Next, let's continue to connect React Solution for communication between components .

Third party data flow framework “ Class representative ”:Redux

Simple cross level component communication , You can use publish subscribe mode or Context API Get it done , With the increasing complexity of applications , There will be more and more states to maintain , The relationship between components is becoming more and more complex , At this time, we can consider introducing a three-party data flow framework , such as Redux.

Redux yes JavaScript State container , It provides predictable state management .

Simply interpret this sentence , First Redux In order to Javascript It was born of application , Which means it's not React Patents , Any framework or native Javascript Both can be used. . We know that state is actually data , The so-called state container , Is a repository for public data .

To understand predictable state management , We need to know first Redux What it is and what its workflow is like .

Redux It mainly consists of three parts :store、reducer and action.

  • store It's a read-only Single data source
  • action Is an object that describes state changes
  • reducer Is a pure function that distributes and processes changes

stay Redux The whole process of work , Data flow is strictly unidirectional ,


Let's understand... From the perspective of coding Redux workflow ,

Use createStore establish store object

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

createStore Accept three inputs :reducer、 Initial state and middleware .

reducer The role of is to bring new state Return to store

reducer Is an acceptance of the old state and change , A pure function that returns a new state , There are no side effects ,

const reducer = (state, action) => newState
 Copy code 

When we base reducer To create store When , It's actually for this store Specifies a set of update rules .

action Its function is to inform reducer “ Let change happen ”

action Is an object that contains its own unique identity , In the vast sea of store In the State Library , Want to hit someone who wants to change state, The correct... Must be used action To drive ,

const action = { type: 'ACTION_TYPE', payload: {} }
 Copy code 

dispatch For distribution action

action Itself is just an object , Want to make reducer Perceive action, Also need to distribute action This action , This action is made by store.dispatch Accomplished ,

 Copy code 

distributed action after , Corresponding reducer Will respond to trigger store Status update in

Related articles

At the end

This article starts with my Blog , Pretty good , Mistakes are inevitable , Please correct any mistakes in the article !

If you have questions or find errors , You can ask questions and make corrections in the comment area ,

If you like or inspire , welcome star, It's also an encouragement to the author .

( End )

copyright notice
author[campcc],Please bring the original link to reprint, thank you.

Random recommended