Vous êtes sur la page 1sur 5

Connecting Redux to your app

Setup a React/Redux app


Create a new React app called 'photo-album':
$ create-react-app photo-album
Move into your app folder (cd photo-album) and add the redux dependencies:
$ npm install redux react-redux
Add a store.js right away (in src/):
1
2
3
4
5
6
7
8
import { createStore } from 'redux'
import reducer from './reducers'

const enhancer = window.__REDUX_DEVTOOLS_EXTENSION__ &&


window.__REDUX_DEVTOOLS_EXTENSION__()

const store = createStore(reducer, enhancer)

export default store


Also add a reducers/ folder with an albums.js:
1
2
3
export default (state = [], action = {}) => {
return state
}
And an index.js:
1
2
3
4
5
6
import { combineReducers } from 'redux'
import albums from './albums'

export default combineReducers({


albums
})
In your App.js wrap the components inside a Provider component (from the react-redux) package:

Redux Actions and action creators


Yesterday we've build some components that dispatched actions. In this chapter we look at a more advanced and
more common approach to dispatching actions from components. After we've done that and cleaned up our code,
it's time for some async Redux actions.

To dispatch actions we have to connect that component to our redux store.

export default connect()(AlbumsListContainer)

Also make sure you import connect from the 'react-redux' package.

Now we just have to do in /actions our actions and create them in a way that are “Action Creators” it means to
dothem as functions like this:

ok like this:

export function helloWorld(firstName, lastName) {


return {
type: 'HELLO_WORLD',
payload: {
firstName: firstName,
lastName: lastName
}
}
}

Store the above function in a new folder actions/ in test.js

And import the action in the container onyou are going to use it.

render() {
return (
<Provider store={store}>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
</Provider>
);
}
In App.js import the Provider component from the react-redux package and the store from store.js.
Run your app like normally, you should see the standard 'Welcome to React' page. Check in the Redux tools and
make sure there's a property 'albums' in your state which contains an empty array.

And Now,

We just have to create dispatch that action to the reducer so we can create a new State.

The way it is done in redux, is by using:

this.props.dispatch(actionCreator())

But it can be done in a way its more efficient that is by using bind action creators.

Bind action creators


A bind action creator is just a better way to make, this.props.dispatch(actionCreator())
To do so we add the next code.
// top of the file:
import { helloWorld } from '../actions/test'

// bottom of the file:


export default connect(null, { helloWorld: helloWorld })
(AlbumsListContainer)

// now inside the component, we can use this:


this.props.helloWorld('Alice', 'Seriously Alice')

We can say that connect gets 2 parameters:

connect(mapStateToProps, mapDispatchToProps)(componentConnected) in this case we


are using the second parameter, and here we are going to pass our action creators like
this:

export default connect(null, {actionCreator_1, actionCreator_2})(connectedComponent)


So now, intead of using:

this.props.dispatch(actionCreator_1());

We will use:

this.props.actionCreator_1();

Be aware that at this point, because we are binding the action to connect, this.props.dispatch() in no
longer available.

Now we just have to import the const that creates the type of the actionCreator and put it in the reducer,
using a swith to go ove the places and changing the state according to the payload we got.

Always remember, an action have an effect if there is a reducer listening to that action.

Next STEP: Setting up mapStateToProps


In order to retrieve the state from the store we will use mapStateToProps, that is a function that
reactRedux provides.

In order to use it we have to set it like this:

export const mapStateToProps = (state) => {

return {

stocks: state.stocksReducer

export default connect(mapStateToProps, { addStock })(Stocks)

Using ASYNC ACTION – Redux Thunk


We have everything set up, but now we want to fetch some data, we were doing it in
componentDidMount, but the problem comes if we want to use that data in other components.

We have to optiosn:
1. We copy the code in every component we want to use the data. (Bad idea cause then we are
duplicating the code.

2. We pass that fetching code into a fucntion actionCreator to put it in the store, (Thats a better
Idea)

The problem is that now we can not access to dispatch() to dispatch that data into the store
from the promise of the fetch data, because of using the bind action creator →
mapDispatchToProps.

To solve this problem we have Redux-thunk, which works like a middleware, allowing the
dispatch method to happen inside a function.

First:

npm install redux-thunk


And then, change the store to apply the middleware, should look like this:

import { createStore, applyMiddleware, compose } from 'redux'


import reducer from './reducers'
import ReduxThunk from 'redux-thunk'

const devTools = window.__REDUX_DEVTOOLS_EXTENSION__ ?


window.__REDUX_DEVTOOLS_EXTENSION__() : f => f

const enhancer = compose(


applyMiddleware(ReduxThunk),
devTools
)

const store = createStore(reducer, enhancer)

export default store

Notice that: intalling the middleware does change how actions work, so the
actionCreators still working the same, we only gain the hability to dispatch a
function as well thanks to redux-thunk midddleware. The rest continues
working the same.

The function to dispatch will receive the dispatcher function like this:

example of ActionCreator dispatching.

export function getAlbums() {


return function (dispatch) {
request('https://jsonplaceholder.typicode.com/albums')
.then(response => {
dispatch(setAlbums(response.body))
})
}
}

Vous aimerez peut-être aussi