SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Front End Workshops
ReactJS - Part II
Flux Pattern & Redux
Cristina Hernández
Jordi Serra
ReactJS Summary
1. Decompose UI into reusable components which
render to virtual DOM
2. ReactJS will sync VDOM to real browser DOM
3. JSX format
4. Can render on client and server
ReactJS Summary - Component Types
const ButtonChange = ({update}) => {
return (
<button onClick={update}>
change
</button>
)
}
class Lannister extends React.
Component{
constructor(props) {
super(props);
this.state = {
motto: "Hear me roar"
};
}
render() {
return (
<div>
<h3>Lannister</h3>
name: {this.props.name} <br/>
motto: {this.state.motto} <br/>
</div>
);
}
}
Flux Pattern
Redux Framework
Predictable state container for JS apps
Redux Flow
Redux - Three Principles
1. Single Source of Truth
The whole application must be described solely using a single
object: state
2. State is Read-only
The only way to change state is to emit an action
3. Changes are made with Pure Functions
Reducers are pure functions → No other variables involved (in or
out)
All actions pass through all reducers → ensure state is consistent
IN STATE WE TRUST
State: Single Source of Truth
$> console.log(store.getState())
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
State is read only
The only way to mutate the state
is to dispatch an action → an object
describing what happened
store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})
State after action
State before action
Changes are made with REDUCERS
Reducers are pure functions.
Actions pass through all reducers
Never mutate state. Always return a new one
import {
combineReducers,
createStore
} from 'redux'
let reducer = combineReducers({ visibilityFilter, todos })
let store = createStore(reducer)
Changes are made with REDUCERS
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [...state, {
text: action.text,
completed: false
}]
case 'COMPLETE_TODO':
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}
function visibilityFilter(state =
'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
Minions App
Connect React with Redux - mapStateToProps
import React, { Component } from 'react';
import { connect } from 'react-redux';
class MinionList extends Component {
createMinionMap() {
return this.props.minionList.map(minion => {
return (<MinionItem key={minion.id} minion={minion} />);
});
}
render() {
return (<ul className="col-md-10">{this.createMinionMap()}</ul>);
}
}
function mapStateToProps(state) {
return {
minionList: state.minionList
}
}
export default connect(mapStateToProps)(MinionList);
containers/minion_list.js
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]) - React-redux
Connects a React component to a Redux store.
It does not modify the component class passed to it. Instead, it returns a new, connected component class, for you to use.
Connect React with Redux - Dispatch Action
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { searchMinion } from '../actions/index';
class SearchBar extends Component {
render() {
return (
<div>
<input onChange={event => this.onInputChange(event.target.value)} />
</div>);
}
onInputChange(term) {
this.props.searchMinion(term);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ searchMinion }, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
containers/search_bar.js
bindActionCreators(actionCreators, dispatch) - Redux
Turns an object whose values are action creators, into an object with the same keys, but with every action creator
wrapped into a dispatch call so they may be invoked directly.
Connect React with Redux - Define Action
export const SEARCH_ACTION = 'SEARCH_ACTION';
actions/types.js
import {
SEARCH_ACTION
} from '../actions/types';
export default function(state=[], action)
{
switch (action.type) {
case SEARCH_ACTION:
//return [action.payload, ...state];
return action.payload;
default:
return state;
}
}
reducers/minion_search.js
import {
SEARCH_ACTION
} from './types';
export function searchMinion(term) {
return {
type: SEARCH_ACTION,
payload: getMinionListByTerm(term)
}
}
actions/index.js
Connect React with Redux - Make store connectable
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import App from './components/app';
import rootReducer from './reducers';
ReactDOM.render(
<Provider
store={createStore(rootReducer)}>
<App />
</Provider>
,
document.querySelector('.container'));
index.js
import { combineReducers } from 'redux';
import minionList from './minion_search';
import minionSelect from './minion_select';
const rootReducer = combineReducers({
minionList: minionList, //minionList
minionSelect: minionSelect //minionSelect
});
export default rootReducer;
reducers/index.js
<Provider store> - React-redux
Makes the Redux store available to the connect() calls in the component hierarchy below.
Connect React with Redux - Make store connectable
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import App from './components/app';
import rootReducer from './reducers';
ReactDOM.render(
<Provider
store={createStore(rootReducer)}>
<App />
</Provider>
,
document.querySelector('.container'));
index.js
import { combineReducers } from 'redux';
import minionList from './minion_search';
import minionSelect from './minion_select';
const rootReducer = combineReducers({
minionList: minionList, //minionList
minionSelect: minionSelect //minionSelect
});
export default rootReducer;
reducers/index.js
createStore(reducer, [initialState], [enhancer]) - Redux
Creates a Redux store that holds the complete state tree of your app.
There should only be a single store in your app.
Connect React with Redux - Make store connectable
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import App from './components/app';
import rootReducer from './reducers';
ReactDOM.render(
<Provider
store={createStore(rootReducer)}>
<App />
</Provider>
,
document.querySelector('.container'));
index.js
import { combineReducers } from 'redux';
import minionList from './minion_search';
import minionSelect from './minion_select';
const rootReducer = combineReducers({
minionList: minionList, //minionList
minionSelect: minionSelect //minionSelect
});
export default rootReducer;
reducers/index.js
combineReducers(reducers) - Redux
The combineReducers helper function turns an object whose values are different reducing functions into a single
reducing function you can pass to createStore.
Workshop 20: ReactJS Part II Flux Pattern & Redux

Mais conteúdo relacionado

Mais procurados

React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
Eldar Djafarov
 

Mais procurados (20)

Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developer
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Creating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with ReactCreating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with React
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-saga
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
 
ReactJs presentation
ReactJs presentationReactJs presentation
ReactJs presentation
 
React redux
React reduxReact redux
React redux
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
React и redux
React и reduxReact и redux
React и redux
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
 

Destaque

Destaque (10)

Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native Introduction
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
ALON AUTOMOTIVE ОСИ
ALON AUTOMOTIVE ОСИALON AUTOMOTIVE ОСИ
ALON AUTOMOTIVE ОСИ
 
ALON AUTOMOTIVE AUTOMATIC SLACK ADJUSTERS
ALON AUTOMOTIVE AUTOMATIC SLACK ADJUSTERSALON AUTOMOTIVE AUTOMATIC SLACK ADJUSTERS
ALON AUTOMOTIVE AUTOMATIC SLACK ADJUSTERS
 
Steps to create image carousel by using angularjs
Steps to create image carousel by using angularjsSteps to create image carousel by using angularjs
Steps to create image carousel by using angularjs
 
ALON AUTOMOTIVE BEARINGS
ALON AUTOMOTIVE BEARINGSALON AUTOMOTIVE BEARINGS
ALON AUTOMOTIVE BEARINGS
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
Atomic design
Atomic designAtomic design
Atomic design
 

Semelhante a Workshop 20: ReactJS Part II Flux Pattern & Redux

Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
Evan Schultz
 

Semelhante a Workshop 20: ReactJS Part II Flux Pattern & Redux (20)

React lecture
React lectureReact lecture
React lecture
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
Manage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's ReduxManage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's Redux
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
Damian Kmiecik - Road trip with Redux
Damian Kmiecik - Road trip with ReduxDamian Kmiecik - Road trip with Redux
Damian Kmiecik - Road trip with Redux
 
Beginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native applicationBeginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native application
 
React outbox
React outboxReact outbox
React outbox
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobX
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence Connect
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
From mvc to redux: 停看聽
From mvc to redux: 停看聽From mvc to redux: 停看聽
From mvc to redux: 停看聽
 

Mais de Visual Engineering

Mais de Visual Engineering (18)

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
 
Workshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte IWorkshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte I
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Workshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototyping
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
 
Workshop 7: Single Page Applications
Workshop 7: Single Page ApplicationsWorkshop 7: Single Page Applications
Workshop 7: Single Page Applications
 
Workshop 6: Designer tools
Workshop 6: Designer toolsWorkshop 6: Designer tools
Workshop 6: Designer tools
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

Workshop 20: ReactJS Part II Flux Pattern & Redux

  • 1. Front End Workshops ReactJS - Part II Flux Pattern & Redux Cristina Hernández Jordi Serra
  • 2. ReactJS Summary 1. Decompose UI into reusable components which render to virtual DOM 2. ReactJS will sync VDOM to real browser DOM 3. JSX format 4. Can render on client and server
  • 3. ReactJS Summary - Component Types const ButtonChange = ({update}) => { return ( <button onClick={update}> change </button> ) } class Lannister extends React. Component{ constructor(props) { super(props); this.state = { motto: "Hear me roar" }; } render() { return ( <div> <h3>Lannister</h3> name: {this.props.name} <br/> motto: {this.state.motto} <br/> </div> ); } }
  • 5. Redux Framework Predictable state container for JS apps
  • 7. Redux - Three Principles 1. Single Source of Truth The whole application must be described solely using a single object: state 2. State is Read-only The only way to change state is to emit an action 3. Changes are made with Pure Functions Reducers are pure functions → No other variables involved (in or out) All actions pass through all reducers → ensure state is consistent
  • 8. IN STATE WE TRUST State: Single Source of Truth $> console.log(store.getState()) { visibilityFilter: 'SHOW_ALL', todos: [ { text: 'Consider using Redux', completed: true, }, { text: 'Keep all state in a single tree', completed: false } ] }
  • 9. State is read only The only way to mutate the state is to dispatch an action → an object describing what happened store.dispatch({ type: 'COMPLETE_TODO', index: 1 }) store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_COMPLETED' }) State after action State before action
  • 10. Changes are made with REDUCERS Reducers are pure functions. Actions pass through all reducers Never mutate state. Always return a new one import { combineReducers, createStore } from 'redux' let reducer = combineReducers({ visibilityFilter, todos }) let store = createStore(reducer)
  • 11. Changes are made with REDUCERS function todos(state = [], action) { switch (action.type) { case 'ADD_TODO': return [...state, { text: action.text, completed: false }] case 'COMPLETE_TODO': return state.map((todo, index) => { if (index === action.index) { return Object.assign({}, todo, { completed: true }) } return todo }) default: return state } } function visibilityFilter(state = 'SHOW_ALL', action) { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter default: return state } }
  • 13. Connect React with Redux - mapStateToProps import React, { Component } from 'react'; import { connect } from 'react-redux'; class MinionList extends Component { createMinionMap() { return this.props.minionList.map(minion => { return (<MinionItem key={minion.id} minion={minion} />); }); } render() { return (<ul className="col-md-10">{this.createMinionMap()}</ul>); } } function mapStateToProps(state) { return { minionList: state.minionList } } export default connect(mapStateToProps)(MinionList); containers/minion_list.js connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]) - React-redux Connects a React component to a Redux store. It does not modify the component class passed to it. Instead, it returns a new, connected component class, for you to use.
  • 14. Connect React with Redux - Dispatch Action import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { searchMinion } from '../actions/index'; class SearchBar extends Component { render() { return ( <div> <input onChange={event => this.onInputChange(event.target.value)} /> </div>); } onInputChange(term) { this.props.searchMinion(term); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ searchMinion }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar); containers/search_bar.js bindActionCreators(actionCreators, dispatch) - Redux Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly.
  • 15. Connect React with Redux - Define Action export const SEARCH_ACTION = 'SEARCH_ACTION'; actions/types.js import { SEARCH_ACTION } from '../actions/types'; export default function(state=[], action) { switch (action.type) { case SEARCH_ACTION: //return [action.payload, ...state]; return action.payload; default: return state; } } reducers/minion_search.js import { SEARCH_ACTION } from './types'; export function searchMinion(term) { return { type: SEARCH_ACTION, payload: getMinionListByTerm(term) } } actions/index.js
  • 16. Connect React with Redux - Make store connectable import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import App from './components/app'; import rootReducer from './reducers'; ReactDOM.render( <Provider store={createStore(rootReducer)}> <App /> </Provider> , document.querySelector('.container')); index.js import { combineReducers } from 'redux'; import minionList from './minion_search'; import minionSelect from './minion_select'; const rootReducer = combineReducers({ minionList: minionList, //minionList minionSelect: minionSelect //minionSelect }); export default rootReducer; reducers/index.js <Provider store> - React-redux Makes the Redux store available to the connect() calls in the component hierarchy below.
  • 17. Connect React with Redux - Make store connectable import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import App from './components/app'; import rootReducer from './reducers'; ReactDOM.render( <Provider store={createStore(rootReducer)}> <App /> </Provider> , document.querySelector('.container')); index.js import { combineReducers } from 'redux'; import minionList from './minion_search'; import minionSelect from './minion_select'; const rootReducer = combineReducers({ minionList: minionList, //minionList minionSelect: minionSelect //minionSelect }); export default rootReducer; reducers/index.js createStore(reducer, [initialState], [enhancer]) - Redux Creates a Redux store that holds the complete state tree of your app. There should only be a single store in your app.
  • 18. Connect React with Redux - Make store connectable import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import App from './components/app'; import rootReducer from './reducers'; ReactDOM.render( <Provider store={createStore(rootReducer)}> <App /> </Provider> , document.querySelector('.container')); index.js import { combineReducers } from 'redux'; import minionList from './minion_search'; import minionSelect from './minion_select'; const rootReducer = combineReducers({ minionList: minionList, //minionList minionSelect: minionSelect //minionSelect }); export default rootReducer; reducers/index.js combineReducers(reducers) - Redux The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.