Вы находитесь на странице: 1из 5

Table

of Contents
Introduction 1.1
Information Flow in a React/Redux application 1.2
Creating Redux applications 1.3

1
Introduction

React-Redux
My personal notes on building a React/Redux application.

2
Information Flow in a React/Redux application

Information Flow in a React/Redux app


Actions are simple objects, that must have a type field:

// actions are just plain objects with a type field


{
type: "ADD_TODO",
text: "Must learn Redux."
}

Action creators return an action :

function addTodo(text){
return ({
type: "ADD_TODO",
text
})
}

Firing an action is done with the dispatch method:

dispatch(addTodo(text))
dispatch(completeTodo(index))

After we fired the action, somebody should catch the action. These are the reducers, or
reducer functions. Before creating the reducers think about the shape of the application state
object. The reducers take the state, and the action, and spit out the next application state.
Important is that reducers MUST NOT mutate the state that they get to their input, they
MUST create an other state and return that state:

function todoApp(state = {}, action){


switch(action.type){
case "ADD_TODO":
return Object.assign({}, state, {
todos: [...state.todos,{text: "Learn Redux"}]
});
//Object.assign(...) creates a new event

default:
return state;
}
}

3
Information Flow in a React/Redux application

It is possible and recommended to combine reducers:

const todoApp = combineReducers({


reducerA,
reducerB
})

So actions contain the information about what happened, reducers change the state of the
application, according to the action. Store is an object that brings them together:

getState() - access to the application state


dispatch(action) - allows state to be updated
subscribe(listener) - registers listeners

We can create stores upon reducers:

import {createStore} from 'redux'


import todoApp from './reducers'
let store = createStore(todoApp)

So far we have attached the reducer to the store, now we can start dispatching actions:

store.dispatch(addTodo("Learn Redux!"));
store.dispatch(addTodo("Learn React!"));

So stores connect reducers and actions, this can be done with third party libraries, like
'react-redux', where we can use the connect method like this:

mapStateToProps(state){
/*Anything returned here will show up as props in the class that is connected via th
e connect method */
return {propsName: state.whateverWeWant}
}
export default connect(mapStateToProps)(todoApp)

4
Creating Redux applications

Just notes yet


Decide upon what component do we need, class based component or functional based
component:

functional based if the component is simple, not getting any data from the server

import React from 'react';


export default (props)=>{
return(
<div>Some element</div>
);
}

class based if it is more complex, if it needs a constructor, if it ajaxes data from the
server

Вам также может понравиться