Share
Embed
Transcript
67 slides
-
React and Flux Building Applications with a Unidirectional Data Flow
Bill Fisher @fisherwebdev -
https://speakerdeck.com/fisherwebdev/flux-meetup "Couch" by Brian Teutsch, used under CC BY 2.0
/ Modified from original -
"Couch" by Brian Teutsch, used under CC BY 2.0 /
Modified from original https://speakerdeck.com/fisherwebdev/flux-meetup -
"Couch" by Brian Teutsch, used under CC BY 2.0 /
Modified from original -
THE PLAN Anatomy of a React + Flux Application Actions
& Action Creators The Dispatcher Stores + Testing Views, Controller-views and React Initialization, Interacting with a Web API, Immutable Data -
. ├── css │ └── app.css
├── index.html ├── js │ ├── actions │ │ └── FooActionCreators.js │ ├── AppBootstrap.js │ ├── AppConstants.js │ ├── AppDispatcher.js │ ├── stores │ │ ├── FooStore.js │ │ └── __tests__ │ │ └── FooStore-‐test.js │ ├── utils │ │ ├── AppWebAPIUtils.js │ │ ├── FooUtils.js │ │ └── __tests__ │ │ ├── AppWebAPIUtils-‐test.js │ │ └── FooUtils-‐test.js │ └── views │ ├── FooControllerView.react.js │ └── FooChild.react.js └── package.json -
js ├── actions │ └── FooActionCreators.js
├── AppBootstrap.js ├── AppConstants.js ├── AppDispatcher.js ├── stores │ ├── FooStore.js │ └── __tests__ │ └── FooStore-‐test.js ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── views ├── FooControllerView.react.js └── FooChild.react.js . ├── css │ └── app.css ├── index.html ├── │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └── package.json -
js ├── actions │ └── FooActionCreators.js
├── AppBootstrap.js ├── AppConstants.js ├── AppDispatcher.js ├── stores │ ├── FooStore.js │ └── __tests__ │ └── FooStore-‐test.js ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── views ├── FooControllerView.react.js └── FooChild.react.js -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
ACTIONS & ACTION CREATORS Actions: an object with a type
property and new data Action creators: semantic methods that create actions collected together in a module to become an API -
// FooActionCreators.js ! var AppDispatcher = require('../AppDispatcher'); var
AppConstants = require('../AppConstants'); ! var ActionTypes = Constants.ActionTypes; ! module.exports = { ! createMessage: function(text) { AppDispatcher.dispatch({ type: ActionTypes.MESSAGE_CREATE, text: text }); } ! }; -
! createMessage: function(text) { AppDispatcher.dispatch({
type: ActionTypes.MESSAGE_CREATE, text: text }); } -
! createMessage: function(text) { AppDispatcher.dispatch({
type: ActionTypes.MESSAGE_CREATE, text: text }); } -
! createMessage: function(text) { AppDispatcher.dispatch({
type: ActionTypes.MESSAGE_CREATE, text: text }); } -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
THE DISPATCHER Essentially a registry of callbacks To dispatch, it
invokes all the callbacks with a payload Flux dispatcher is a singleton; payload is an action Primary API: dispatch(), register(), waitFor() Base class is available through npm or Bower. -
// AppDispatcher.js ! var Dispatcher = require('Flux.Dispatcher'); !
// export singleton module.exports = new Dispatcher(); -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
Store stores ├── FooStore.js └── __tests__
└── FooStore-‐test.js STORES -
STORES Each store is a singleton The locus of control
within the application Manages application state for a logical domain Private variables hold the application data Numerous collections or values can be held in a store -
STORES Register a callback with the dispatcher Callback is the
only way data gets into the store No setters, only getters: a universe unto itself Emits an event when state has changed -
// FooStore.js ! var _dispatchToken; var _messages =
{}; ! class FooStore extends EventEmitter { ! constructor() { super(); _dispatchToken = AppDispatcher.register((action) => { ! switch(action.type) { ! case ActionTypes.MESSAGE_CREATE: var message = { id: Date.now(), text: action.text } _messages[message.id] = message; this.emit('change'); break; ! case ActionTypes.MESSAGE_DELETE: delete _messages[action.messageID]; this.emit('change'); break; ! default: // no op } ! }); } ! getDispatchToken() { return _dispatchToken; } ! getMessages() { return _messages; } ! } ! module.exports = new FooStore(); _dispatchToken = AppDispatcher.register((action) => { ! switch(action.type) { ! case ActionTypes.MESSAGE_CREATE: var message = { id: Date.now(), text: action.text } _messages[message.id] = message; this.emit('change'); break; ! case ActionTypes.MESSAGE_DELETE: delete _messages[action.messageID]; this.emit('change'); break; ! default: // no op } ! }); -
_dispatchToken = AppDispatcher.register((action) => { !
switch(action.type) { ! case ActionTypes.MESSAGE_CREATE: var message = { id: Date.now(), text: action.text } _messages[message.id] = message; this.emit('change'); break; ! case ActionTypes.MESSAGE_DELETE: delete _messages[action.messageID]; this.emit('change'); break; ! default: // no op } ! }); -
TESTING STORES WITH JEST Stores have no setters — how
to test is not obvious Jest is Facebook’s auto-mocking test framework Built on top of Jasmine -
jest.dontMock('FooStore'); ! var AppConstants = require('AppConstants'); ! var
ActionTypes = AppConstants.ActionTypes; ! describe('FooStore', function() { ! var callback; ! beforeEach(function() { AppDispatcher = require('AppDispatcher'); FooStore = require('FooStore'); callback = AppDispatcher.register.mock.calls[0][0]; }); ! it('can create messages', function() { callback({ type: ActionTypes.MESSAGE_CREATE, text: 'test' }); var messages = FooStore.getMessages(); var firstKey = Objects.keys(messages)[0]; expect(FooStore.getMessages()[firstKey].text).toBe(‘test’); }); ! }); callback = AppDispatcher.register.mock.calls[0][0]; -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
js ├── │ ├── AppBootstrap.js ├──
AppConstants.js ├── ├── │ │ │ ├── utils │ ├── AppWebAPIUtils.js │ ├── FooUtils.js │ └── __tests__ │ ├── AppWebAPIUtils-‐test.js │ └── FooUtils-‐test.js └── ! actions └── FooActionCreators.js AppDispatcher.js stores ├── FooStore.js └── __tests__ └── FooStore-‐test.js views ├── FooControllerView.react.js └── FooChild.react.js Dispatcher Action Store View -
VIEWS & CONTROLLER VIEWS Tree of React components Controller views
are near the root, listen for change events On change, controller views query stores for new data With new data, they re-render themselves & children -
getDefaultProps() getInitialState() componentWillMount() render() componentWillReceiveProps()* shouldComponentUpdate()
componentWillUpdate() render() DOM Mutations Complete componentDidMount() componentDidUpdate() componentWillUnmount() Lifecycle: Mounting and Unmounting Update: New Props or State *Called only with new props -
getDefaultProps() getInitialState() componentWillMount() render() componentWillReceiveProps()* shouldComponentUpdate()
componentWillUpdate() render() DOM Mutations Complete componentDidMount() componentDidUpdate() componentWillUnmount() Lifecycle: Mounting and Unmounting Update: New Props or State *Called only with new props -
! ! var React = require('react'); ! ! !
! ! ! ! ! ! module.exports = FooControllerView; // FooControllerView.react.js var FooControllerView = React.createClass({ ! render: function() { // TODO } ! }); -
// FooControllerView.react.js var FooControllerView = React.createClass({ !
render: function() { // TODO } ! }); -
// FooControllerView.react.js var FooControllerView = React.createClass({ !
componentDidMount: function() { FooStore.on('change', this._onChange); }, ! componentWillUnmount: function() { FooStore.removeListener('change', this._onChange); }, ! render: function() { // TODO } ! }); -
// FooControllerView.react.js var FooControllerView = React.createClass({ !
getInitialState: function() { return { messages: FooStore.getMessages() }; }, ! componentDidMount: function() { FooStore.on('change', this._onChange); }, ! componentWillUnmount: function() { FooStore.removeListener('change', this._onChange); }, ! render: function() { // TODO } ! _onChange: function() { this.setState({ messages: FooStore.getMessages() }); }, ! }); -
var FooControllerView = React.createClass({ ! getInitialState: function() {
return { messages: FooStore.getMessages() }; }, ! componentDidMount: function() { FooStore.on('change', this._onChange); }, ! componentWillUnmount: function() { FooStore.removeListener('change', this._onChange); }, ! ! _onChange: function() { this.setState({ messages: FooStore.getMessages() }); }, ! }); // FooControllerView.react.js render: function() { // TODO } -
render: function() { var messageListItems = this.state.messages.map(message =>
{ return ( <FooChild key={message.id} id={message.id} text={message.text} /> ); }); return ( <ul> {messageListItems} </ul> ); }, -
// FooChild.react.js ! var React = require('react'); !
var FooChild = React.createClass({ ! propTypes = { id: React.PropTypes.number.isRequired, text: React.PropTypes.string.isRequired } ! render: function() { return ( <li>{this.props.text}</li> ); } ! }); ! module.exports = FooChild; -
INITIALIZATION OF THE APP Usually done in a bootstrap module
Initializes stores with an action Renders the topmost React component -
module.exports = function(/*object*/ data, /*DOMElement*/ elem) { !
var dispatchToken = AppDispatcher.register(action => { if (action.type !== Constants.ActionTypes.INITIAL_LOAD) { return; } ! // wait for all the stores to initialize before rendering var tokens = [ ContentStore, FriendStore, LoggingStore, ThemeStore, ].map(store => store.getDispatchToken()); AppDispatcher.waitFor(tokens); ! React.render(<AppRoot />, elem); ! AppDispatcher.unregister(dispatchToken); }); Actions.initialize(data); // Creates INITIAL_LOAD action }; -
CALLING A WEB API Use a WebAPIUtils module to encapsulate
XHR work. Start requests directly in the Action Creators, or in the stores. Important: create a new action on success/error. Data must enter the system through an action. -
FLUX Dataflow Programming CQRS Functional and FRP MVC Reactive WHERE
DOES FLUX FIT IN