React integrates native Redux (2)

Time:2020-1-18

React integrates native Redux (2)

Preface

A basic application framework has been completed to integrate native Redux (1) in react, but when distributing action, logic cannot be written in action. In other words, action is always just a JSON object, not a function. Although logic methods can be written in view life cycle to change the value of state, in the long run, it will cause project overstaffing and maintenance difficulties, so real T-thunk middleware is born from this

Project creation

Integrating native Redux with react (1)

Add dependency package

yarn add redux-thunk -s

SRC file directory

|-app.js
|-store.js
|-index.js
|-actions.js

There is an additional actions.js file, in which actions with logic are stored

Action.js content

// actions.js
/**
 *Redux thunk action is in the form of a function. The return value is the function using dispatch
 *Basic format
 * function () {
 *  return function (dispatch) {
 *    dispatch(...)
 *  }
 * }
 */
export const fetchListAction = param => {
  return dispatch => {
    //Simulate asynchronous request data (fetch, Axios, etc.)
    new Promise(resolve => {
      setTimeout(() => {
        const data = {
          code: 0,
          msg: "ok",
          data: {
            list: ["hello", "thunk"],
            param
          }
        };
        resolve(data);
      }, 2000);
    }).then(result => {
      dispatch({ type: "SAVE", payload: result.data });
    });
  };
};

Store changes

Introduction of Redux thunk

Complete code

// store.js
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
Import {composewithdevtools} from "Redux devtools extension"; // Chrome Redux debugging tool

//State initial value
const initState = {
  list: ["a", "b"]
};

//Reducer format
const reducer = (state = initState, action) => {
  const { type, payload } = action;
  //Type processing of action
  if (type === "SAVE") {
    return Object.assign({}, state, payload);
  }
  return state;
};

/**
 *Instantiate store
 *Parameter 1: Reducer
 *Parameter 2: Middleware
 */
export default createStore(
  reducer,
  composeWithDevTools(applyMiddleware(thunk))
);

Call in app.js

Mainly this paragraph

useEffect(() => {
    store.dispatch(fetchListAction({ id: 1 }));
}, []);

Complete code

// app.js
import React, { useState, useEffect } from "react";
import store from "./store";
import { fetchListAction } from "./actions";

export default () => {
  //Get the state in the store and put it into the hook function, similar to this. Setstate (store. Getstate())
  const [state, setState] = useState(store.getState());
  useEffect(() => {
    //Store subscription function, which is automatically executed when state changes through store.dispatch distribution action
    store.subscribe(() => {
      Setstate (store. Getstate()); // reset the value of component state to update the view
    });
  }, []; / [] means only one execution

  //Simulate first load page request data
  useEffect(() => {
    store.dispatch(fetchListAction({ id: 1 }));
  }, []);

  const { list } = state;

  const addList = () => {
    list.push(Date.now());
    Store. Dispatch ({type: 'Save', payload: {list}}); // distribute an action object
  };

  return (
    <div>
      <button onClick={addList}>add</button>
      <ul>
        {list.map(v => {
          return <li key={v}>{v}</li>;
        })}
      </ul>
    </div>
  );
};

In this way, you can meet the needs of general small and medium-sized projects and view the complete code

General large-scale projects use Redux saga, please see react integration native Redux (3)

Recommended Today

[reading notes] calculation advertising (Part 3)

By logm This article was originally published at https://segmentfault.com/u/logm/articles and is not allowed to be reproduced~ If the mathematical formula in the article cannot be displayed correctly, please refer to: Tips for displaying the mathematical formula correctly This article isComputing advertising (Second Edition)Reading notes. This part introduces the key technology of online advertising, which is […]