Redux

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Redux process

Action > Reducer > New State

Action Creator

Action creators are just functions. To achieve separation of concerns and make our code more reusable we use action creators to create these actions in a separate file. So then instead of creating the action in our controller we simply call the action creator function in our component. ** Don't forget to import the file where you defined your creator functions.

.subscribe()

Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState() to read the current state tree inside the callback.

Map dispatch to Props 2/3

After adding the function to the Props, we want to call the function via a button.

Action Example

An action is just a javascript object and it has a type property which described the action. It also has an optional payload of data. First we create an action and store it in a constant. We set the type property to a string in capital letters that is descriptive, then we pass an optional payload.

Reducers note

An important thing to note about reducers is that they are pure functions. Let's remember the characteristics of pure functions: 1. Pure functions are only determined by their input values 2. Pure Functions have no side effects. By this we mean pure functions do not have any effect outside of the function. They only return a value.

Payload

Any kind of data we want to pass along with the dispatch action.

Default Dispatch Behavior

By default mapDispatchToProps is just dispatch => ({ dispatch }). So if you don't specify the second argument to connect(), you'll get dispatch injected as a prop in your component.

Dispatch Action

Describes the change we want to make to the state.

Redux DevTools

First, just Google for Redux Devtools Chrome. There you will find the Chrome extension for Redux. Please download it, and refresh Chrome. You will know that you have installed the extension if you go to your developer console in Google Chrome (press command+shift+c to pull it up), and then at the top bar you will see a couple of arrows. Click those arrows, and if you see Redux as your dropdown, you properly installed the Chrome extension. Step one is done. Second, we need to tell our application to communicate with this extension. Doing so is pretty easy. Now we change the arguments to our createStore method to the following: window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(). Ok, notice that we are still passing through our reducer to the createStore method. The second argument is accessing our browser to find a method called __REDUX_DEVTOOLS_EXTENSION__.

1. Create a Controlled Form Using State and an onChange Event Handler

First, we made sure the React component of our application was working. We did this by building a form, and then making sure that whenever the user typed in the form's input, the state was updated.

mapStateToProps

Gives our components access to the stores state as a prop.

mapDispatchToProps

Gives our components access to use actions as props.

Interacting with the state.

If we want to make a change to the state, we have to dispatch an action from our component. The action will contain a type and an optional payload (like an id of the object we want to delete).

@@INIT

Initial action type. We get two benefits: an initial rendering of the state, and the ability to set our initial state in our reducer.

combineReducers()

Redux's combineReducers() function will allow us to write separate reducers for each of the resources in our application. Each reducer is passed to the combineReducers() function, which will produce a single reducer

2. On Submission of Form, Dispatch an Action to the Store

Second, We connected the component to Redux and designed our mapDispatchToProps

Create a store example

Skeleton for creating a store. Create a constant for the initial state, create a reducer function that takes in a state and action. We also set the initial state as the state default in the parameters. Lastly we create a constant, store that calls the createStore we imported with the reducer function as an argument.

Displaying todos

The CreateTodo component is handling the creation side of things, so let's make a new component where we'll be getting todos from the store. We'll call this TodosContainer and connect it to Redux. Now our TodosContainer is mapping over the todos it received from Redux, passing the value of each todo into a child component, Todo. Todo in this case doesn't have any Redux related code, and is a regular, functional component.

uuid

The Node UUID package for this to create random unique ids.

Provider

The Provider is a component that comes from our React Redux library. It wraps around our App component. It does two things for us. The first is that it will alert our Redux app when there has been a change in state, and this will re-render our React app.

ownProps

The components current props before we add the state from the redux store.

connect()

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store. whatever function we pass as the first argument to that connect() function is called each time there is a change of state, and has access to the entire store's state. The connect() function then takes the return value from the mapStateToProps() function and adds that return value to the props of the component that is passed through in the last parentheses. import { connect } from 'react-redux'

.createStore()

The createStore(), method however is generic across Redux applications. It always returns a store (given a reducer) that will have a dispatch method and a getState method.

Reducer

The reducer takes in the action, looks at the type of action and takes the data to update the state. It is a pure function that interacts with the store (the central data store) in order to change the state or data inside of it. It is important to note that a reducer never updates the previous state, but rather created a new state object.

3. Update State

Third, we built our reducer such that it responded to the appropriate event and concatenated the payload into our array of todos.

.getState()

This method simply returns the state so we can use it elsewhere in our application.

Redux: Thunk

Thunk handles asynchronous calls when working with Redux. Thunk allows us to return a function inside of our action creator. Normally, our action creator returns a plain JavaScript object, so returning a function is a pretty big change. That function receives the store's dispatch function as its argument. With that, we can dispatch multiple actions from inside that returned function.

Manipulating state according to the action.

Using an if statement in our reducer, we check what type of action we get and then update the state by creating a new array and drop in our current state using the spread operator and with that our new state. Don't forget to pass in the information you didn't change by using the spread operation to drop in the current state.

Store Setup

We want to import createStore() in our src/index.js file, where ReactDOM renders our application. To avoid passing store as a prop, we use the Provider component. The Provider component wraps the top level component, App, in this case, and is the only component where store is passed in.

Map dispatch to Props 1/3

We want to return an object, the object will represent the functions we're going to map to the props of the component.

Component State vs Store State

When architecting a user interface, try to use local state and parent props first. If we end up constantly passing down tons of props, we should consider connecting the component in question with a Redux store.

Map to dispatch 3/3

When the button is clicked our function dispatches our action to the reducer, and now we actually take care of the state change in the reducer.

Updating state.

When we want to update that data, we must send an action, which is a set of strict instructions we create that Redux will use for how to update it. Here, we can imagine that after a user fills out a form and clicks submit, we will create an action that tells Redux how to incorporate the update into the state. Any time we update the state in Redux, we must create an action first.

Presentational vs Container Components

While it is possible to connect any component to our store, one pattern is to only connect Container components. Since they are primarily concerned managing state and actions that mutate the state of an app, they tend to be a good place to connect to the store. Presentational components are modular, reusable (and typically small) components that are concerned with "how stuff looks". In this pattern, they are not typically connected to a store.

createStore() under the hood.

With this set up, we've got a fully functional store, that encapsulates our state and provides a controlled way to write (dispatch) and retrieve (getState) information. Every piece of code that would be common to any JavaScript application following this pattern is wrapped inside of the createStore function. Any code that is particular to our application is outside that function. What's particular to a specific application? How the DOM is updated in our render function What events trigger a dispatch method How our state should change in response to different actions being dispatched. These are all implemented outside of our createStore function. What is generic to each application following this pattern? That a call to dispatch should call a reducer, reassign the state, and render a change. This is implemented inside the createStore function.

.dispatch()

dispatch() is the method used to dispatch actions and trigger state changes to the store. dispatch() is the method used to dispatch actions and trigger state changes to the store.

To use Redux Thunk you would need to install the NPM package:

npm install --save redux-thunk First we have index.js, which now imports thunk and applyMiddleware and uses them when creating the Redux store.

Installing Redux into React

you need to install two packages, redux and react-redux by running npm install redux && npm install react-redux. Then all you need to do is run npm install && npm start to get started.


संबंधित स्टडी सेट्स

Basic Livestock Surgical Procedures

View Set

Szülésznő tesztsor 401-500 (I. Egyszerű feleletválasztás)

View Set

Chapter: Chapter 14: Implementing

View Set

Quiz 6: Marketing Information and Research

View Set

Chapter 4: Software Requirements Elicitation

View Set