react integrates native redux

react integrates native redux(1)

Project Creation

create-react-app reduxdemo

Dependency packages

yarn add redux -s

thinking

  1. Creating a globally unique store through redux
  2. Getting the required data through the store
  3. Distributing action objects through dispatch causes store state changes
  4. Change the view layer through store subscribe

src file directory

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

Delete index.js

Projects created through create-react-app have a lot of useless things. First, clean up the src directory as above, and then streamline index.js as follows

// index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./app";

ReactDOM.render(<App />, document.getElementById("root"));

Create a store

store.js is the core file of redux. This article is used for learning. It does not emphasize code breakdown, so reducer and store are written together.

// store.js
import { createStore, applyMiddleware } from "redux";
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;
};

/**
 * Instance store
 * Parameter 1: reducer
 * Parametric 2: Middleware
 */
export default createStore(reducer, composeWithDevTools(applyMiddleware()));

Application code app.js

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

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

  const { list } = state;

  const addList = () => {
    list.push(Date.now());
    store.dispatch({ type: "SAVE", payload: { list } }); //Distributing an action object
  };

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

action objects are formatted as json objects and must have type attributes or errors will be reported: Error: Actions may not have an undefined "type" property. Have you misspelled a constant?

Carry data is usually payload attribute, which is not mandatory

Such a basic react redux is integrated, see Complete code

Tags: Javascript React JSON Attribute

Posted on Wed, 09 Oct 2019 11:11:59 -0700 by zemerick