Redux

The installation

# NPM
npm install redux
# Yarn
yarn add redux
Copy the code

state

  • State is where the data is stored
  • State data must passreducerTo manage the
  • The reducer request needs to passdispatch
  • The dispatch argument is oneaction

In summary, changing the state requires initiating an action through Dispatch and then returning a new state through reducers.

Action

  • Actions are the payload for transferring data from the app to the Store and are the only source of store data.
  • Need to pass throughstore.dispatch()willactiontostore
  • In the format, type is a fixed field. Other fields can be customized
// A simple action function
const ADD_TODO = 'ADD_TODO';function addTodo(payload) {
    return {
        type: ADD_TODO, // This is usually a constant to avoid writing errors
        payload, // Data to be sent to the reducer}}/ / usage
dispatch(addTodo(0))
Copy the code

Reducer

Reducers specifies how changes in application state can be sent to the Store in response to actions. Remember that Actions only describe the fact that something happened, not how the application updates state.

designstatestructure

  • In Redux applications, all states are stored in a single object.

The Action to deal with

  • You need to tell by type how do you need to modify the data, call different methods
  • When modifying state data, only the new state can be returned, and state data cannot be directly modified
  • Reducers takes two arguments, state and the object returned by the Action
const ADD_TODO = 'ADD_TODO';
// Initialize state
const initialState = {
    todos: []}// Process toDOS data
function todos(state = [], action) {
    switch (action.type) {
        case ADD_TODO: 
        return [
            ...state,
            ...action.payload
        ]
        default: 
            return state
    }
   return state;
}

// Allocate the state data to different methods. Each function handles only part of the state. If the business and data are separated, it can be split in this way
function todoApp(state, action) {
    return {
        todos: todos(state.todos, action)
    }
}

Copy the code

Modular reducers

In the excessive reducers, it can be divided through different modules, and then combined through combineReducers.

All combineReducers() does is generate a function that calls your series of reducers, each reducer filters a portion of the state data based on their keys and processes it. This generated function then merges all the reducer results into one large object.

import { combineReducers } from 'redux'

const todoApp = combineReducers({
    todos, Todos is the name of the module. To access data in todos, you need todos.todos
})
// todoApp is written the same way
function todoApp(state, action) {
    return {
        todos: todos(state.todos, action)
    }
}

export default todoApp
Copy the code

Namespace problem

Since Redux does not use namespace to distinguish modules, and modules are sold to root store when diapatch is made, all reducer reducer will be triggered. Therefore, the format of type should be well defined among modules

Store

  • Maintain application state;
  • Provide the getState() method to getState;
  • Provide a dispatch(action) method to update state;
  • Register a listener with subscribe(listener);
  • Unsubscribe the listener via a function returned by subscribe(listener).

Create the state

import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp) // Get all the states
Copy the code

Initiate an Action to update the data

import { addTodo } from './actions'
// This allows you to modify the todos value
store.dispatch(addTodo('learn about actions'))
Copy the code

react-redux

The installation

npm install --save react-redux
Copy the code

Into the Store

  • throughProviderThe container passes store into the component
  • It is best to place the container component in the root component
import React from 'react'
import { Provider } from 'react-redux'
import store from './store/index'
import App from './compontns/App'

render(
    <Provider store={store}>
        <App/>
    </Provider>.document.getElementById('root'))Copy the code

State data is used in the component

  • throughconnectInject methods such as state and Dispatch into the component
  • Connect takes two parametersmapStateToProps,mapDispatchToProps
  • mapStateToPropsPhi is a function, acceptstateAs an argument, returns an object
  • mapDispatchToPropsIs a function: takes two arguments, one isdisaptchThe other is for the current componentprops
  • mapDispatchToPropsObject: The key value should be a function that is treated asactionIs automatically emittedaction
// connect
import { connect } from 'react-redux'

// State is the total state
const mapStateToProps = state= > {
    return {
        todos: state.todos  // Return todos to the props of the component with key todos}}const mapDispatchToProps = (dispatch, ownProps) = > {
    return {
    // If this method returns, props can be used to get this method
        onClick: () = > {
            dispatch({
                type: ADD_TODO,
                payload: ownProps.todos
            })
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Home)// Home is the name of the current component
Copy the code

redux-saga

The installation

npm install redux-sage

yarn add redux-saga
Copy the code

Introduction to the

  • Redux-saga is a middleware that manages the operations of a Redux application
  • Redux-saga is created using a generator function

configuration

import {createSrote, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducers from './reducers';
import rootSaga from './saga' / / saga file

const sageMiddleware = createSagaMiddleware();
// Introduce saga into store
let store = createStore(reducers, applyMiddleware(sagaMiddleware));
/ / run saga
sagaMiddleware.run(rootSaga);

export default store;

Copy the code

Saga method of writing

import { call, put, takeEvery } from 'redux-saga/effects'

const getData = () = > {
    // Call performs asynchronous operations
    const products = yield call(Api.fetch, '/products')
    // put initiates an action similar to dispatch
    yield put({
        type: ADD_TODO,
        payload: products
    })
}

function *stateSaga() {
    yield takeEvery(ADD_TODO, getData)
    yield takeEvery(ADD_TO, getInfo)
}

export const stateSaga = () = >{}Copy the code

conclusion

  • react-reduxAfter the action is initiated, the listener will process the actionactionThe back andreducerThe previous step
  • takeEveryMultiple getData instances are allowed to start simultaneously
  • If you want to intercept multiple actions, use multipletakeEveryRegardless of order, this can be triggered at the same time.