Professional Documents
Culture Documents
TP - Tuto: Actions - Js
TP - Tuto: Actions - Js
The question is: how do we achieve the same functionality using Redux?
In the remainder of this simple exercise , we’ll look at one way of doing it. This
is, of course, a simple example, and so all the code could go into a single file.
However, to help distinguish the different parts of Redux,
you’ll separate the main functionalities into different files corresponding to
their steps in the ‘Redux flow’ above.
actions.js
We’ll start by defining our actions. An action can be an object or, as in our case,
a simple string. We need one action to increment our counter, and one action to
decrement it, so create a file called actions.js and add the following:
Simple!
reducers.js
Next, we need to specify how the application’s state should change in response
to each action.
This is where we can record our initial state, which is an object just like what
you’d expect in a regular React state. Create a file called reducers.js and add in
the following:
const initialState = {
number: 1
};
Next, we need to create our reducer function. This takes two arguments:
a state;
TP - Tuto 1
It’s common to pass in our initial state as the default argument, and this is also
where we import our actions. The final code for reducers.js should look like
this:
Note that it’s common to use switch statements to distinguish action types
here, but regular if and else statements will work fine too.
store.js
Up til now, we haven’t needed to install the redux and react-
redux dependencies, but we’ll need them to set up our store. Type the following
into your terminal:
App.js
Now that we’ve exported our store we need to import it into App.js , by
passing it into React-Redux’s Provider component:
TP - Tuto 2
import React from 'react';
import { Provider } from 'react-redux';import Counter from './Counter';
import store from './store';
import './App.css';function App () {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}export default App;
This means that any child of the Provider component can access our store and,
therefore, our actions and reducers.
Counter.js
Finally, we need to connect our Counter component to our store, which we can
do by importing connect (which is a higher order function) from the react-
redux module:
The connect function must be used to export any component that needs to
access to change Redux state.
TP - Tuto 3
Lastly, we can use the dispatch prop (by calling this.props.dispatch ) to link each
method of our component with an action:
addOne = () => {
this.props.dispatch({ type: 'ADD_ONE' });
}minusOne = () => {
this.props.dispatch({ type: 'MINUS_ONE' });
}
And that’s everything. The overall code in Counter.js should look something like
this:
If you’ve done everything correctly, your counter should now be working!
TP - Tuto 4