Redux details

Time:2020-11-25

Redux details

React components refers to component components

Store is the common area where data is stored

This process is like borrowing books in the library

React ComponentsWhen I borrow books in the library, I want to tell the librarian what books I want to borrowAction CreatorsWhat kind of books do you want to borrow? The librarian is the librarianStoreIn charge of the book management of the whole library, the librarian can’t remember the storage of all the books in the library. Generally, there is a system. If you want to borrow any books, you will check whether there are any books. This system isReducers

Redux usage

  1. storeIt’s the only one
  2. onlystoreBe able to change your content
  3. ReducerMust be a pure function

    • Pure function means that given a fixed input, there must be a fixed output, and there will be no side effects

install

yarn add redux

newly buildstore/index.js

import { createStore } from "redux";
import reducer from "./reducer";

const store = createStore(reducer);
export default store;

newly buildstore/reducer.js

//Set default data according to business
const defaultState = {
  inputValue: "",
  list: [],
};
/**
 *
 *State the data of the entire store and the store before modification
 *Action
 */
export default (state = defaultState, action) => {
  if (action.type === "change_input_value") {
    const newState = JSON.parse(JSON.stringify(state));
    newState.inputValue = action.value;
    return newState;
  }
  return state;
};
//Tip: reducer can accept state, but it can never change state

use

store.getState () // read

const action = {
    type: 'change_input_value',
    value: e.target.value
}
store.dispatch(action)

store.subscribe ( this.handleChange )// the component subscribes to the store and passes a function. As long as the store data changes, this function will be executed
handleChange(){
    this.setState(store.getState())
}

Split actiontypes

newly buildstore/actionTypes

export const CHANGE_INPUT_VALUE = change_input_value;

Split actioncreators

newly buildstore/actionCreators

import {CHANGE_INPUT_VALUE} from './actionTypes'
export const getInputChangeAction = (value) => ({
    type: CHANGE_INPUT_VALUE
    value
})

Sending Ajax requests using react thunk Middleware

// actionCreators
export const initListAction = (data) => ({
    type: INIT_LIST_ACTION,
    data
})

export const getTodoList = () => {
    return (dispatch) => {
        axios.get('/list.json').then(res => {
            const data = res.data
            const action = initListAction(data)
            dispatch(action)
        })
    }
}

//Components
componentDidMount() {
    const action = getTodoList()
    store.dispatch(action)
}

What is Redux middleware

Redux details

The view will dispatch an action in redux. The action is passed to the store through the dispatch method of the store. The store receives the action and passes it to the reducer along with the previous state. The reducer returns a new data to the store, and the store changes its state. This is a standard process of redux.

In this process, Redux middleware refers to the relationship between action and store. In Redux, action can only be an object, so action is an object directly sent to the store. After Redux thunk is used, action can be a function, and action is passed to store through dispatch method. So who is the relationship between action and store? Is it the dispatch method? In fact, what we mean by middleware is the encapsulation of the dispatch method.

When we encapsulate the dispatch method, such as using the middleware Redux thunk, when you call the dispatch method and the parameters passed to the dispatch method are objects, then the dispatch method will directly pass the object to the store; at this time, if you pass it to the dispatch method When the method is a function, the function will not be passed to the store directly. It will let the function execute first. When the store needs to be called after the execution, the function will call the store

Redux saga Middleware

newly buildstore/sagas.js

// actionCreators.js
export const initListAction = (data) => ({
  type: INIT_LIST_ACTION,
  data,
});

// store/sagas.js
import { takeEvery, put } from "redux-saga/effects";
import { GET_INIT_LIST } from "./actionTypes";

function* getInitList() {
  const res = yield axios.get("/list.json");
  const action = initListAction(data);
  yield put(action);
}

function* todoSagas() {
  yield takeEvery("GET_INIT_LIST", getInitList);
}

export default todoSagas;
// store/index.js
import createSageMiddleware from "redux-sage";
import todoSagas from "./sagas.js";

const sageMiddleware = createSagaMiddleware();
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__();
const enhancer = composeEnhancers(applyMiddleware(sageMiddleware));

const store = createStore(reducer, enhancer);
sagaMiddleware.run(todoSagas);

export default store;
//Components
componentDidMount() {
    const action = getTodoList()
    store.dispatch(action)
}

Redux practical application

// index.js
import store from "./store";
const App = () => {
  <Provider store={store}>
    <TodoList />
  </Provider>;
};

//Components
import React, { Component } from "react";
import { connect } from "react-redux";

class TodoList extends Component {
  render() {
    <div>
      <div>
        <input
          value={this.props.inputValue}
          onChange={this.props.changeInputValue}
        />
        < button > submit
      </div>
    </div>;
  }
}

const mapStateToProps = (state) => {
  return {
    inputValue: state.inputValue,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    changeInputValue(e) {
      const action = {
        type: "change_input_value",
        value: e.target.value,
      };
      dispatch(action);
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

// reducers.js
export default (state = defaultState, action) => {
  if (action.type === "change_input_value") {
    const newState = JSON.parse(JSON.stringify(state));
    newState.inputValue = action.value;
    return newState;
  }
  return state;
};

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]