Putting it all together

Let's quickly look at the source files that bring everything together to give you a sense of completeness. Let's start with index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Root from './components/Root';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Root />, document.getElementById('root'));
registerServiceWorker();

This looks just like most index.js files in create-react-app that you've worked with so far in this book. Instead of rendering an App component, it's rendering a Root component. Let's look at this next:

import React from 'react';
import { Provider } from 'react-redux';
import App from './App';
import store from '../store';

const Root = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

export default Root;

The job of Root is to wrap the App component with a Provider component from react-redux. This component takes a store prop, which is how you're able to ensure that connected components have access to Redux store data.

Let's take a look at the store prop next:

import { createStore } from 'redux';
import reducers from './reducers';

export default createStore(
  reducers,
  window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__()
);

Redux has a createStore() function that builds a store for your React app. The first argument is the reducer function that handles actions and returns the new state of the store. The second argument is an enhancer function that can respond to changes in store state. In this case, you want to check if the Redux DevTools browser extension is installed and if it is, then connect it to your store. Without this step, you won't be able to use browser tooling with your Redux app.

We're almost done. Let's look at the reducers/index.js file that combines your reducer functions into one function:

import { combineReducers } from 'redux';
import app from './app';
import home from './home';
import newBook from './newBook';
import bookDetails from './bookDetails';

const reducers = combineReducers({
  app,
  home,
  newBook,
  bookDetails
});

export default reducers;

Redux has only one store. In order to subdivide your store into slices of state that map to the concepts of your application, you name the individual reducer functions that handle the various slices of state and pass them to combineReducers(). With this app, your store has the following slices of state that can be mapped to components:

  • app
  • home
  • newBook
  • bookDetails

Now that you've seen how this app is put together and how it works, it's time to start instrumenting it with the Redux DevTools browser extension.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.246.203