Learning React.js: Understanding the structure of flux,react.js

Source: Internet
Author: User
Tags emit

Getting to Know Flux, the React.js Architecture

Ken Wheeler (@ken_wheeler)

Brief Introduction

Welcome to the third chapter of learning React. Today we will learn how to work with the Facebook Flux structure and how we should use it in our projects.

If you are not ready, I strongly recommend you go back to see the first and second chapters of this series, Getting Started & Concepts and Building a Real time Twitter Stream with Node and React. Of course I'm not forcing you, but if you're not familiar with React.js, these two articles are certainly useful to you.

What is Flux?

Flux is a structure that is used inside the facial book to work with React. It's not a frame or a library. It's just a new system structure that works with React, and the concept of single-stream.

That is to say, the Facebook provides a repo that contains the Dispatcher library. This library is used to focus on all the global, broadcast messages to the announcement/Subscribe mode of the registration event.

A typical use case for a FLUX structure is to create an event system with the NodeJS Eventemitter module for managing the applied state.

The best way to explain Flux I think it should be to introduce its components to the following:

    • Actions– the methods of assisting the Dispatcher
    • Dispatcher– receiving and broadcasting to registered Heather events
    • stores– use the container of State & logic to store the place where the heather event is registered
    • Controller views–react components, used to receive state from the Stores, and then pass it through props to the subassembly.

Let's look at the schematic:

What's the API for?

When you need to use the numbers from outside (or send out), I find that the most painless way to use the Actions to introduce the numbers to the flux flow and then to Stores.

Dispatcher

What the hell is that Dispatcher ?

Dispatcher is the basis for managing the entire process. It's your centrum of the Newark core. Dispatcher receives the actions and then pushes the actions and statistics to the heather of the registration.

Is that the release/subscribe?

It's not exactly like this. Despatcher Broadcast to all registration heather, and can allow you to follow a certain order to adjust the heather, and even before doing a pause to wait for updates. There is only one despatcher in your application, and its responsibility is to play your core Centrum Newark.

Look like this:

<!-- lang: js -->var Dispatcher = require(‘flux‘).Dispatcher;var AppDispatcher = new Dispatcher();AppDispatcher.handleViewAction = function(action) {  this.dispatch({    source: ‘VIEW_ACTION‘,    action: action  });}module.exports = AppDispatcher;

In the example above, we created a Dispatcher example and created a handleViewAction method. This abstraction is useful if you want to find out what the visual touch does to the/api of the vs service .

Our method is to adjust the dispatch method, which will be broadcast to action all registration heather. This action can be used in Stores, and then the update of state will be touched.

To describe it, it should look like this:

The Dispatcher module has a cool feature that can be relied upon and managed heather in Stores. So if the update of one part of your application needs to be updated first, the Dispatcher method will be waitFor very useful.

In order to use this function, we need to save the return value of the Dispatcher registration method in the Store in the dispatcherIndex form as follows:

<!-- lang: js -->ShoeStore.dispatcherIndex = AppDispatcher.register(function(payload) {});

And then in our store, when we're dealing with something, we can use the Dispatcher method to make waitFor sure our shoe store is updated:

<!-- lang: js -->case ‘BUY_SHOES‘:  AppDispatcher.waitFor([    ShoeStore.dispatcherIndex  ], function() {    CheckoutStore.purchaseShoes(ShoeStore.getSelectedShoes());  });  break;
Stores

In Flux, Stores manages the state of a particular part of your application. Or in layman's parlance, including every part of the use, the storage of management numbers, the use of heather, and the adjustment of the parameters.

Let's take a look at the most basic Store:

<!--lang:js-->var appdispatcher = require (' ... /dispatcher/appdispatcher '); var shoeconstants = require ('.. /constants/shoeconstants '); var eventemitter = require (' Events '). Eventemitter;var merge = require (' React/lib/merge ');//Internal object of Shoesvar _shoes = {};//Method to load shoes fro M Action datafunction loadshoes (data) {_shoes = data.shoes;} Merge our store with Node's Event emittervar shoestore = Merge (Eventemitter.prototype, {//Returns all shoes getshoe  S:function () {return _shoes;  }, Emitchange:function () {this.emit (' change ');  }, Addchangelistener:function (callback) {This.on (' change ', callback);  }, Removechangelistener:function (callback) {This.removelistener (' change ', callback);  }});//Register Dispatcher Callbackappdispatcher.register (function (payload) {var action = payload.action;  var text; Define-do-certain actions switch (action.actiontype) {case shoeconstants.load_shoes://Call Inter Nal Method basedUpon dispatched action Loadshoes (Action.data);    Break  Default:return true;  }//If action is acted upon, emit change event shoestore.emitchange (); return true;}); Module.exports = Shoestore;

The most important thing we do in the above code is to NodeJS our store with the eventemitter . This allows our store to listen to/broadcast events. Allow our images/components to be updated based on these events. Because our controller view is listening to the Store and using these events to change, we can let controller view know whether our application state has changed and whether it should be refreshed to keep it consistent.

We also use it to register a register heather to our AppDispatcher . This means that our Store is now listening to broadcasting AppDispatcher . Our switch section is used to determine whether or not to send out broadcasts when events occur. If a related action happens, then an update event is pushed, and the watch that listens to this event will update their state of the situation.

Our public method getShoes is provided to our Controller View for enquiries, it is used to look up _shoes all the shoes in the image, and then to provide us with the status of the set. Although this is just a simple example, the complex logically can also be placed here so that our vision and help remain intact.

Action Creator and Actions

An action creator is a set of motion that is used to send to Dispatcher in View (or wherever it is going to be done). The motion will be pushed through the dispatcher.

The face book is like this with its, action-type constants used to decide what action to use, and what action to match. In the registration heather, these actions can be used to interact with each other, and can be counted as arguments to adjust these movements with the action of the motion.

To see the definition of constants:

<!-- lang: js -->var keyMirror = require(‘react/lib/keyMirror‘);module.exports = keyMirror({  LOAD_SHOES: null});

We used the React library, right keyMirror , you guessed it, it was used to match our key. To look at this file, we can tell us how to load the shoes. With this static help, you can keep everything organized, and you can see what's going on in a higher level. ".

Now look at the definition of the Action Creator:

<!-- lang: js -->var AppDispatcher = require(‘../dispatcher/AppDispatcher‘);var ShoeStoreConstants = require(‘../constants/ShoeStoreConstants‘);var ShoeStoreActions = {  loadShoes: function(data) {    AppDispatcher.handleAction({      actionType: ShoeStoreConstants.LOAD_SHOES,      data: data    })  }};module.exports = ShoeStoreActions;

In our example above, we ShoeStoreActions created a method in the image, and then we used the numbers we provided to adjust the push motion. We can now bring this motion file into our vision or API and then use it to ShoeStoreActions.loadShoes(數據) push it to the Dispatcher and then be broadcast. After that, Shoestore will ' hear ' the event and then add the shoes!

Controller views

The Controller views are nothing to say, they are React components that are used to listen to events, and then deal with the state of Stores. They pass through the props to send the numbers to the sub-components.

Look like this:

<!-- lang: js -->/** @jsx React.DOM */var React = require(‘react‘);var ShoesStore = require(‘../stores/ShoeStore‘);// Method to retrieve application state from storefunction getAppState() {  return {    shoes: ShoeStore.getShoes()  };}// Create our component classvar ShoeStoreApp = React.createClass({  // Use getAppState method to set initial state  getInitialState: function() {    return getAppState();  },  // Listen for changes  componentDidMount: function() {    ShoeStore.addChangeListener(this._onChange);  },  // Unbind change listener  componentWillUnmount: function() {    ShoesStore.removeChangeListener(this._onChange);  },  render: function() {    return (      <ShoeStore shoes={this.state.shoes} />    );  },  // Update view state when change event is received  _onChange: function() {    this.setState(getAppState());  }});module.exports = ShoeStoreApp;

In the example above, we have passed the addChangeListener event change, and when we receive the event, we update our application status.

Our status is stored in Stores, so we use the public method of Stores to receive and set the status.

put a piece

Now that we have individually passed the various parts of the FLUX structure, we should have a better understanding of how this structure is actually working. Remember that picture we saw before? Let's take a closer look at it and now we understand what each step of the process is doing:

Packaging

After reading this article, I hope that if you do not have a "knowledge" of the Facebook of the FLUX structure, now you can say you know. It's only after you actually use it to do something that you'll know what React.js is.

Once you've used flux, you don't have to use flux to write React, like manipulating the DOM without having to go crazy with jQuery. Of course you can do it, but it's not good enough to be structured.

If you want to use the flux structure, but you do not want to use React, to see DeLorean, a flux framework, you can use Ractive.js or Flight. There are other repositories worth looking at, such as Fluxxor, which provides a different flux approach, and in flux, the center provides a set of tightly coupled flux components.

Well, I'm sure you've really mastered Flux and you've actually got it, so we're going to use reach.js and Flux to create a shopping station in the fourth chapter of learning React.

Learning React.js: Understanding the structure of flux,react.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.